पाठ 24 / 25

Running Tests in CI

No watch mode, parallel workers and sharding.

Fast, non-interactive and split across machines

In CI, tests must run once and exit with a non-zero code on failure. vitest run disables watch mode (Vitest also detects CI environments); Jest runs once unless you pass --watch, and --ci changes snapshot behaviour so missing snapshots fail instead of being written. Both runners execute test files in parallel workers; tune with --maxWorkers (Jest) or the pool and worker options in Vitest (check the docs for your version), since CI machines often have fewer cores than laptops. For large suites, shard: --shard=1/4 runs a quarter of the test files, so four CI jobs share the work; Vitest can merge sharded results with its blob reporter. Cache node_modules or the package manager store, emit JUnit reports for the CI UI, and upload coverage as an artefact.

A sharded GitHub Actions job

YAML with the commands each shard runs.

name: unit-tests
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        shard: [1, 2, 3, 4]
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm
      - run: npm ci
      - run: npx vitest run --shard=${{ matrix.shard }}/4 --reporter=default --reporter=junit --outputFile.junit=reports/junit.xml
        env:
          TZ: UTC
      # Jest equivalent:
      # - run: npx jest --ci --shard=${{ matrix.shard }}/4 --maxWorkers=2

Same command locally and in CI

Put the CI invocation in an npm script (test:ci) so a developer can reproduce a CI failure exactly, including the time zone and reporter settings.

त्वरित जाँच: What does --shard=2/4 do?

  • Runs only tests with "2" in the name
  • Runs each test four times
  • Runs the second quarter of the test files so four jobs can split the suite
  • Uses two workers on four CPUs
Answer

Runs the second quarter of the test files so four jobs can split the suite — Sharding splits work across machines.