DEV Community

Darkø Tasevski
Darkø Tasevski

Posted on Originally published at darkotasevski.dev

Running only the Jest specs a commit can affect

This one is about making a pre-commit hook faster without making it useless, in a fairly large React component library (around 980 spec files, Jest running in ESM mode, CSS modules everywhere, and lefthook running the hooks). The hook ran tsc and then the whole test suite on every commit, which took almost four minutes, and that's the same four minutes whether you changed a component or fixed a typo in a README.

The obvious fix, and the one you'll find in pretty much every answer about this, is jest --findRelatedTests. You give it a list of files, it walks Jest's dependency graph backwards and runs only the specs that import those files, directly or through other modules. Together with lefthook's glob (so a job only starts when a matching file is staged) the core of the first version looked like this:

pre-commit:
  jobs:
    - name: types-check
      glob: "*.{js,jsx,ts,tsx,json,cjs,mjs}"
      run: npm run types:check

    - name: test
      glob: "{src,buildUtils}/**/*.{js,jsx,ts,tsx,json,cjs,mjs}"
      run: npm run --silent test -- --findRelatedTests --passWithNoTests {staged_files}
Enter fullscreen mode Exit fullscreen mode

There was also a job that ran the full suite when the Jest config or setup files changed. Docs commits went from minutes to well under a second, and a commit that touched a small leaf component ran a handful of specs instead of a thousand. The idea behind the globs was that a style or docs change can't break a test, so there's no reason to run anything for it. That assumption didn't survive long, and most of this post is about the places where it broke.

What the dependency graph can't see

--findRelatedTests only knows about edges between files that Jest itself resolves, and Jest only indexes the extensions in moduleFileExtensions (js, jsx, ts, tsx, json, node and a couple more by default). Everything else is invisible to it, even when a spec very much depends on it. The easiest way to find the gaps was to stage a real edit, or ask Jest directly with --listTests --findRelatedTests <file>, and see what would run, so each of these comes from a probe like that.

CSS imports. The header component relates to over 700 of the roughly 980 specs, because half the library renders a header somewhere. Its styles.module.css relates to 0, because .css isn't in moduleFileExtensions, so the edge from the component to its stylesheet doesn't exist as far as --findRelatedTests is concerned. The CSS transform still runs when a spec imports the component (that's how the class names get mapped), it's only the reverse lookup that misses it.

Specs that read files through fs. One spec compared a few layout constants in JS (a header height and some z-indexes) against the CSS variables in the global stylesheets, with a plain readFileSync and a regex, so the JS side and the actual CSS can't drift apart. A "style-only" change to --header-height broke that spec, and the hook stayed green, because there's no import anywhere for Jest to follow. A few other specs did the same kind of thing with HTML fixtures and JSON files they load by path.

Recorded HTTP responses. About 40 specs replay recorded API responses from a mocks.json file next to them, loaded through a small helper that takes a path. Most of them sit in the same folder as their tape, one reached across into another component's folder. Staging only a tape ran nothing, since, again, nothing imports it, and grepping the specs for fs doesn't find them either, because the file read happens inside the helper.

Setup files. A helper imported only by jest.setup.js relates to 0 specs, even though the setup file runs before every single spec, and in this case the helper wraps expect for the whole suite. Same for Jest's config, the CSS transformer and the PostCSS config, which can change the result of any spec without being imported by any of them.

Deleted files. When you delete a module, it's gone from the graph, so there's nothing to walk backwards from. tsc catches most broken imports after a deletion, but not the importers of a deleted CSS module (CSS modules are typed generically, so any .css import type-checks), and not paths that only exist as strings, like the ones passed to jest.mock or to the tape helper.

And one gap that wasn't Jest's fault at all. The test job's glob skipped src/index.ts, which is the library's entry point. In lefthook a single * already matches across /, so src/**/*.ts wants at least one folder between src/ and the file, and the most important file in the repo didn't match. I checked it in a scratch repo with both lefthook versions I had around (1.12 and 2.2), and src/*.ts matched both src/index.ts and src/a/b.ts, so that's the pattern you want if you mean "any TS file under src".

Picking the run with a small script

Once it was clear that a glob can't express any of this, the test job became a small Node script that reads the staged files and decides between three outcomes, which are the full suite, the related specs plus a few extras, or nothing. The job has no glob anymore, since the script has to see root-level files like jest.config.mjs or package.json to know when to run everything, and lefthook would skip the job before the script ever saw them. The hook ended up like this (trimmed to the relevant jobs):

pre-commit:
  jobs:
    # formatters with stage_fixed run first, so the checks below read the fixed files
    - name: fix
      group:
        parallel: true
        jobs:
          - name: fix-code
            glob: "*.{js,ts,tsx,json,cjs,mjs}"
            run: npx biome check --write {staged_files}
            stage_fixed: true
          - name: fix-style
            glob: "**/*.css"
            run: npx stylelint --fix {staged_files}
            stage_fixed: true

    - name: verify
      group:
        parallel: true
        jobs:
          - name: types-check
            glob: "*.{js,jsx,ts,tsx,json,cjs,mjs}"
            run: npx tsc --noEmit --incremental --tsBuildInfoFile "$(git rev-parse --git-path precommit.tsbuildinfo)"
          - name: test
            run: node scripts/precommit-tests.mjs
Enter fullscreen mode Exit fullscreen mode

tsc runs next to the tests with --incremental, and its cache lives in the git directory, which keeps one cache per worktree. I had several worktrees sharing one node_modules through a symlink, and with the cache in node_modules/.cache each worktree kept overwriting the others' paths, so switching worktrees cost a 56 second tsc run instead of 5.

The script itself gets the staged files from git, as two lists:

import { execFileSync } from 'node:child_process';

const git = args => execFileSync('git', [...args, '-z'], { encoding: 'utf8' }).split('\0').filter(Boolean);
const changed = filter => git(['diff', '--cached', '--name-only', '--no-renames', `--diff-filter=${filter}`]);

const staged = changed('ACM'); // added, copied, modified
const deleted = changed('D');
Enter fullscreen mode Exit fullscreen mode

--no-renames reports a rename as a deletion plus an addition, so the old path counts as deleted (and a renamed source file sends the commit to the full suite, which is what we want, since the old importers are broken now). -z stops git from quoting paths with non-ASCII characters, which would otherwise match none of your patterns. Then the decision, written out in a simpler shape than the real thing but with the same rules:

import { dirname } from 'node:path';

const RUNS_EVERYTHING = [/^jest\.(config|setup|globalSetup)\./, /^postcss\.config\./, /^tsconfig\.json$/, /^package(-lock)?\.json$/];
const IS_SPEC = /\.(spec|test)\.[jt]sx?$/;
const IS_MODULE = /\.(jsx?|tsx?|cjs|mjs)$/;
const IN_JEST_GRAPH = /\.(jsx?|tsx?|cjs|mjs|json)$/; // JSON is imported as a module, but tapes are JSON read by path
const UNDER_SRC = /^src\/.+(?<!\.md)$/; // anything a spec could observe, docs excluded
const lastTwo = file => file.split('/').slice(-2).join('/'); // specs name tapes by relative path

// specs: [{ path, source }]; setupImports: repo paths of the files the setup files import
function pickRun({ staged, deleted, specs, setupImports }) {
  const touchesEverything = file => RUNS_EVERYTHING.some(rule => rule.test(file)) || setupImports.includes(file);
  const deletedSource = deleted.some(file => UNDER_SRC.test(file) && !IS_SPEC.test(file));
  if ([...staged, ...deleted].some(touchesEverything) || deletedSource) return { mode: 'all' };

  const inputs = staged.filter(file => UNDER_SRC.test(file));
  if (inputs.length === 0) return { mode: 'none' };

  const readers = specs.filter(spec => /\b(readFileSync|readFile|readdirSync|globSync)\b/.test(spec.source));
  const nonModules = inputs.filter(file => !IS_MODULE.test(file)); // CSS, HTML, JSON tapes
  const neighbours = specs.filter(spec =>
    nonModules.some(file => dirname(spec.path) === dirname(file) || spec.source.includes(lastTwo(file))),
  );

  return {
    mode: 'related',
    files: [...new Set([...inputs.filter(file => IN_JEST_GRAPH.test(file)), ...readers.map(s => s.path), ...neighbours.map(s => s.path)])],
  };
}
Enter fullscreen mode Exit fullscreen mode

The related case then runs jest --findRelatedTests --passWithNoTests with those files, so Jest still walks the graph for the modules, and the spec files we add ourselves simply relate to themselves. The specs that read from disk are found by grepping their sources, which is crude, but there were only about five of them, so running all of them on any non-doc change costs almost nothing. setupImports comes from reading the relative imports out of the setup files, which saves keeping a list by hand, but it only catches direct imports, so a helper two levels down (or one under a folder like test-utils/) needs its own entry in RUNS_EVERYTHING.

For a staged stylesheet that means the specs that read files from disk, plus every spec in the stylesheet's own folder. That's only a heuristic, since the CSS transform builds the class names from the file's content, and a spec somewhere else that cares about a class name can still notice a CSS change, which is one of the reasons the full suite still runs in CI.

A spec deleted in the working tree but not yet staged is still in git ls-files, so reading every spec's source crashed the hook for every unrelated commit until there was an existsSync check in front of it. And keep in mind that both Jest and tsc read the working tree, not the index, so an unstaged change can make a commit pass or fail that it shouldn't, which is one more thing only CI catches.

Numbers

Measured on real commits after the change:

  • A docs-only commit takes 0.1-0.4s.
  • A CSS-only commit takes 3.5s.
  • A broken CSS variable is blocked in 2.8s, by the spec that reads the stylesheet.
  • Deleting a CSS module that's still imported runs the full suite and fails in 186s, compared with about 231s for the old hook, where tsc and the tests ran one after the other.
  • tsc with --incremental takes 16s without a cache and 5s with a warm one.

The one case that stays slow is a change to a small utility that's re-exported through a big barrel file. A util behind a 133-export barrel that 314 files import still relates to about 720 of the 978 specs, so for that commit --findRelatedTests saves very little. That comes from the barrel file, and fixing it means changing the library's imports, since the hook can't do much about it.

Summary

--findRelatedTests is the right base for a fast pre-commit hook, but it answers "which specs import this file", which is narrower than "which specs can this change break". Anything Jest doesn't resolve as a module (stylesheets, fixtures and tapes loaded by path, setup files, deleted files) needs its own rule, and the quickest way to find those rules in your repo is to grep the specs and your test helpers for fs calls, look at what your setup files import, and then stage one real edit of each kind of file and check what the hook really runs. And keep running the full suite in CI anyway, because the hook only covers the cases someone thought to write a rule for.

Top comments (0)