← Back to Jest Mastery
Advanced16 min read

Jest in CI/CD

Run Jest reliably in continuous integration with caching, sharding, and reporting.

CI Configuration Basics

Run jest --ci in pipelines for non-interactive mode with frozen snapshots. Set CI=true environment variable so Jest adjusts defaults (no watch, fail on deprecated APIs).

Install dependencies with lockfile for reproducible installs. Run tests on every pull request before merge.

# GitHub Actions excerpt
- run: npm ci
- run: npm run test:ci
  env:
    CI: true

Workers and Sharding

Control parallelism with --maxWorkers—CI runners vary in CPU count. Shard large suites across jobs with --shard=1/4 syntax (Jest 28+) to reduce wall clock time.

Balance shard count against job startup overhead—four shards on thousand tests often sweet spot.

  • Each shard runs subset of test files—combine coverage carefully
  • Use --forceExit only as last resort for hanging handles
  • --detectOpenHandles helps fix root cause of hangs
jest --ci --shard=2/4 --maxWorkers=2

Caching

Cache node_modules and Jest cache directory in CI for faster reruns. Jest cache invalidates on config and transformer changes.

Turbo and Nx remote cache extend to test tasks in monorepos—only rerun affected projects on changed files.

# Cache key includes lockfile hash
actions/cache@v4:
  with:
    path: node_modules
    key: npm-${{ hashFiles('package-lock.json') }}

Coverage and Reporting

Upload coverage artifacts to codecov or similar. Fail build on coverageThreshold regression. JUnit reporter integrates with CI test result UI.

Annotate PRs with failed test names and links to logs. Store HTML coverage as artifact for reviewer access.

jest --ci --coverage --reporters=default --reporters=jest-junit

Monorepo Strategies

Run Jest per package with workspace tools (pnpm filter, npm workspaces). Root jest projects array maps multiple configs.

Shared setupFilesAfterEnv and custom matchers live in internal test-utils package imported by packages.

  • Fail fast on main branch test breaks before deploy
  • Run full suite nightly even if PR runs affected-only subset
  • Pin Node version in .nvmrc and CI matrix

Get In Touch


Ready to discuss your next project? Drop me a message.