Speed up Jest execution by only running tests impacted by a change.
Beta The plugin is under active development; options and the cache format may change between releases. Please report any issues in the GitHub repository
npm install --save-dev @useblacksmith/jestWrap your Jest config:
// jest.config.js
const { withBlacksmith } = require('@useblacksmith/jest')
module.exports = withBlacksmith({
testEnvironment: 'node',
})Then run jest as before. Worker processes, --runInBand and --workerThreads
are supported. Requires Node 22.15 or newer and Jest 29 or newer.
- Modules. Jest gives every test file a module registry of its own. The
plugin sets the config's
runtimeto a subclass of Jest's that notes every file Jest loads as a module of the test file, CommonJS or ESM. - Files and processes. Files the test file reads through
node:fs, and the modules and reads of the node processes it starts, are recorded too. - Selection. The config's
testSequencerdrops the test files nothing changed for. A test file runs when it has no record, when a file it depends on changed, or when one of its tests failed the last time. - Changes. The recorded files are compared by content with what they were
when the record was made, so files git ignores (
dist/) work too. -t. A run with--testNamePatternruns part of a test file. After a change the file stays selected until a run without the pattern passes.- Installed packages. The record names the packages a test file loaded,
transitive ones included, each with the version in its
package.json. After an install, a test file reruns when one of its packages has another version or is gone. Lockfiles are not compared, and apackage.jsonchange that only touches its dependency fields reruns nothing by itself. A new version of a package Jest's own process or a transformer loaded runs everything.
A tsconfig*.json in a directory below the project reruns the test files that
loaded a file under that directory. So does a package.json, when the fields
modules resolve by change (exports, imports, type, main, name). A change to
anything else in a package.json reruns only the test files that read the
file themselves or that a dependencies rule maps it to.
Changes to the jest, babel or browserslist field of package.json, to
tsconfig.json, jest.config.*, babel.config.*, .babelrc, .swcrc, the
workflow file, or anything the config file imports or globalSetup loads or
reads run everything. So does a run with coverage, and watch
mode is left to Jest.
Each run ends with a summary of what it ran and skipped and how it ended, then the same as JSON for whatever collects the job's logs:
[blacksmith] summary: passed; ran 28 of 540 test files, skipped 512 unaffected; tests: 310 passed, 0 failed, 2 skipped; dependency cache restored, saved; plugin took 1.2s
[blacksmith] run {"v":1,"plugin":"@useblacksmith/jest","version":"1.0.0","runner":"jest","outcome":"passed","files":{"total":540,"affected":28,"skipped":512,"ran":28,"failed":0},...}
The outcome is that of the tests and of coverage thresholds. A
globalTeardown that throws or a testResultsProcessor that fails the run
makes Jest exit non-zero after a summary that says passed.
The second argument of withBlacksmith:
| Option | |
|---|---|
dependencies |
Test file glob → globs of files those test files depend on that nothing reads, e.g. { 'test/db/**': 'migrations/**' }. Paths are relative to the repository root. |
maxShards |
The largest --shard count accepted, 20 by default; a run split further fails. Each shard looks up the records of all shards up to this number. |
cacheKey |
Metadata used for skipping is keyed by working directory, test configuration and runtime (Node major version, OS, architecture). Set this if you need additional granularity, e.g. a job matrix that runs the same suite against different databases, services or environment variables. |
A change to a file does not rerun every test file that loaded it. The plugin records, for each test file, which top-level functions it entered in every module it loaded, and looks at what a change actually touched:
| What changed in the file | Test files that rerun |
|---|---|
The body of a top-level function (function f() {}, const f = () => {}) |
Those that called the function |
| Another top-level declaration (a constant, a class, an enum), or a function's parameter list | Those that loaded a module importing it by name, through re-exports too. A namespace import, a require, a dynamic import() or a jest.mock of the module counts as importing every name |
One key of an object literal held in a const (const FLAGS = { A: 'a', B: 'b' }): changed, added or removed |
Those that called a function reading that key as FLAGS.A, or using the object in any other way (FLAGS[name], Object.values(FLAGS), passing it on), in the file or in a module importing it by name. Those that loaded a module doing so outside a function, too. Any other object counts as one declaration: one with a spread, a computed key, an accessor, a method or a function value |
| Types, comments, or a new declaration nothing uses yet | None. A type annotation inside a class that has a decorator is not a type here: emitted decorator metadata makes it a value, so it counts as a change to the class |
| A new import | Those that had not loaded the imported module |
Any other top-level statement, an export *, or declarations that changed places |
All that loaded the file |
A value built from a changed one counts as changed, and a function that mentions a changed value reruns the test files that called it. A change to a file the plugin cannot take apart reruns every test file that loaded it: CommonJS modules, files using eval, files that take an inline snapshot or mention Function, and anything that is not JavaScript or TypeScript. So does any change in a run with coverage, or of more than one project. A CommonJS module passes on a change to a value only from the modules it requires with a literal path.
To record function entries the plugin adds one call at the start of each top-level function before the project's transformer sees the module. Line numbers stay as they are; a column on the first line of a function moves right by the length of the added call (about 60 characters). The call does nothing outside its module, so a function turned into text with toString() still runs wherever that text is evaluated. Jest caches the transformed module as usual, so the cost is paid once per changed file. The record is kept beside the dependency record and travels with it. It holds file names and hashes, not source: every function, constant, object key and export name is stored as a hash salted with the repository's name, as is every hash of code.
What narrowing cannot see: a test whose result depends on a function's source text or length rather than on calling it.
A changed top-level value that calls something as it is evaluated (a call, new, a tagged template, an assignment, a decorator, a class's static initializer) reruns every test file that loaded the module, since the call may have done more than make the value. So does an unchanged value built from a changed one. A value of literals, objects, arrays, functions and other names reruns only the test files that loaded a module importing it. So does a value whose calls are shown to change nothing but what they make: the language's own reads (Object.values, filter, map, new Set and the like) of consts of literals declared in the same file, with callbacks and functions of the same file that write only to their own variables and to arrays they made themselves, and that call nothing else. Anything that cannot be shown this way (an imported function, a method of an unknown value, a loop that may not end, a const declared before some other call ran) counts as a call that may have done more.
- The plugin sets
runtime,testSequencerandpassWithNoTests, and adds a reporter. A config that setsruntimeortestSequenceritself is refused, and--reporterson the command line replaces the plugin's reporter, which stops the record from updating. - In
projects, inline project objects are wrapped. A project given as a path needsruntime: require.resolve('@useblacksmith/jest/runtime')in its own config. - A package is known by its directory and version. Not seen: a package
changed in place at the same version (
patch-package, a git orfile:dependency) and a package installed outside the repository. A copy installed later in front of the one a test loaded (inside a workspace, as Yarn and npm do for a version that differs from the hoisted one, or inside the package that loads it) counts as a change. With pnpm, which links each name to one of the versions it keeps side by side, a package also counts as changed when a link that led to it now leads to another version. - A test that reads
package.jsonthrough a helper package reruns on any change to it, unless the helper reads it while being imported. - What a test reaches over the network (a database, a mock server) is not
recorded; map it with
dependencies. - A file that a module of Jest's own process (a custom transformer, a custom environment) reads once and keeps is recorded for the first test file of that process only. Babel, SWC and TypeScript config files are exempt: a change to one, in any directory, runs everything.
- For any child process a test starts, the command and the arguments that
name files are recorded. What the child reads beyond those is recorded only
if it is node; for another program (a shell script, a binary), map it with
dependencies. - A child process started with an
envthat dropsNODE_OPTIONSis recorded by its command line only. - A Jest that a test starts with the same config runs every test file it matches and keeps no record of its own: what it loads and reads is recorded for the test file that started it.