Testing & Code Quality

Jest Setup & Deployment Guide

Popular JavaScript testing framework – write unit and API tests with mocks and coverage, then run them in CI as a deployment gate.

Updated Official documentation ↗

1. Introduction & use cases

Jest is a JavaScript testing framework created at Meta. It includes everything in one package: a test runner, assertion library (expect), mocks and spies, snapshot testing, fake timers and code coverage. It works for Node.js back-ends and – with jsdom – for React components.

Jest runs CommonJS out of the box; native ES modules and TypeScript need small extra setup (shown below). For Vite projects, Vitest offers a Jest-compatible API with less configuration.

Where it is used

  • Unit tests for functions, services and utilities
  • API tests for Express/NestJS with supertest
  • React component tests with Testing Library
  • Snapshot tests for serialisable output

2. Prerequisites

You needVersion / notes
Node.jsCurrent LTS release
A JavaScript/TypeScript projectWith code you want to test
EditorVS Code with the Jest extension (optional)

3. Local setup

  1. 1Install Jest

    Add it as a dev dependency and a test script.

    BASH
    npm install --save-dev jest
    npm pkg set scripts.test="jest"
  2. 2ES modules or TypeScript?

    For import/export without a transpiler, run Jest with Node’s VM modules flag. For TypeScript, add ts-jest.

    BASH
    # ES modules ("type": "module")
    npm pkg set scripts.test="node --experimental-vm-modules node_modules/jest/bin/jest.js"
    
    # TypeScript
    npm install --save-dev ts-jest @types/jest typescript
    npx ts-jest config:init

4. Create & run a project

  1. 1Write code and a test

    Test files end in .test.js (or live in __tests__/).

    JS
    // src/price.js
    export function withGst(amount, rate = 18) {
      if (amount < 0) throw new Error('amount must be positive');
      return Math.round(amount * (1 + rate / 100) * 100) / 100;
    }
    
    // src/price.test.js
    import { withGst } from './price.js';
    
    describe('withGst', () => {
      test('adds 18% by default', () => {
        expect(withGst(1000)).toBe(1180);
      });
      test('supports other rates', () => {
        expect(withGst(100, 5)).toBe(105);
      });
      test('rejects negative amounts', () => {
        expect(() => withGst(-1)).toThrow('positive');
      });
    });
  2. 2Mock a dependency

    jest.fn() records calls; mocks keep tests fast and independent of networks or databases.

    JS
    test('sends a welcome email', async () => {
      const send = jest.fn().mockResolvedValue({ ok: true });
      await registerUser({ email: 'a@example.com' }, { send });
      expect(send).toHaveBeenCalledWith(expect.objectContaining({ to: 'a@example.com' }));
    });
  3. 3Test an Express API with supertest

    Export the app without calling listen so tests can use it directly.

    JS
    npm install --save-dev supertest
    
    // test/api.test.js
    import request from 'supertest';
    import app from '../src/app.js';
    
    test('GET /health returns ok', async () => {
      const res = await request(app).get('/health');
      expect(res.status).toBe(200);
      expect(res.body).toEqual({ status: 'ok' });
    });
  4. 4Run tests and coverage

    Watch mode re-runs related tests on save.

    BASH
    npm test
    npx jest --watch
    npx jest --coverage

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

Jest sets NODE_ENV=test if it is not set. Use a separate .env.test (or explicit test config) so tests never touch production databases or APIs.

.env
NODE_ENV=test
DATABASE_URL=postgres://test:test@localhost:5432/app_test
PAYMENT_API_URL=http://localhost:4010   # mock server

Key dependencies

Package / toolUsed for
jestRunner, expect, mocks, coverage
ts-jest / babel-jestTypeScript / transpilation
jest-environment-jsdomBrowser-like environment for DOM/React tests
@testing-library/reactUser-centric component tests
supertestHTTP assertions against Express apps

Folder structure

project structure
project/
├── src/
│   ├── price.js
│   └── price.test.js   # tests next to code
├── test/
│   └── api.test.js      # integration tests
├── jest.config.js
└── coverage/            # generated report

Essential commands

CommandWhat it does
npx jestRun all tests
npx jest --watchRe-run on changes
npx jest path/to/fileRun one file
npx jest -t "name"Run tests matching a name
npx jest --coverageCoverage report in coverage/
npx jest --ciCI mode (no snapshot writing, no watch)

6. Production deployment

Test frameworks are not deployed to a production server – in production they act as a quality gate: they run automatically in CI on every push and pull request, publish reports, and block the deployment when a test fails.

Server & hosting requirements

RequirementRecommendation
CI runnerGitHub Actions / GitLab CI / Jenkins with the same Node.js version as development
Installnpm ci from the lockfile
GateTest job marked as a required check before merge/deploy
ReportsJUnit XML / HTML / coverage uploaded as artifacts

Deployment steps

  1. 1Set a coverage threshold

    Fail the run if coverage drops below the agreed level.

    jest.config.js
    /** @type {import('jest').Config} */
    export default {
      testEnvironment: 'node',
      collectCoverageFrom: ['src/**/*.js'],
      coverageThreshold: { global: { lines: 80, branches: 70 } },
      reporters: ['default', ['jest-junit', { outputDirectory: 'reports' }]],
    };
  2. 2Run the tests in CI on every push

    Tests protect production only if they run automatically. This GitHub Actions workflow installs dependencies and runs the suite on every push and pull request; mark the job as a required check in branch protection so failing code cannot be merged or deployed.

    .github/workflows/tests.yml
    name: tests
    on:
      push:
        branches: [main]
      pull_request:
    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-node@v4
            with:
              node-version: lts/*
              cache: npm
          - run: npm ci
          - run: npx jest --ci --coverage
  3. 3Keep the reports

    Upload coverage and JUnit results so they appear in the run summary.

    YAML
          - uses: actions/upload-artifact@v4
            if: always()
            with:
              name: test-reports
              path: |
                coverage/
                reports/
  4. 4Block deploys on failure

    Make the deploy job depend on tests (needs: test) and require the check in branch protection – see CI/CD Pipeline.

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ npm test PASS src/price.test.js withGst ✓ adds 18% by default (2 ms) ✓ supports other rates ✓ rejects negative amounts (1 ms) PASS test/api.test.jsTest Suites: 2 passed, 2 totalTests: 4 passed, 4 totalTime: 0.912 s
Figure 1: terminal output of the sample Jest project (section 4).
1Write tests2npm test locally3CI: jest --ci--coverage4Reports +threshold5Deploy only ifgreen
Figure 2: production deployment flow (section 6).
project/├── src/│ ├── price.js│ └── price.test.js # tests next to code├── test/│ └── api.test.js # integration tests├── jest.config.js└── coverage/ # generated report
Figure 3: project folder structure (section 5).

8. Common errors & solutions

SyntaxError: Cannot use import statement outside a module

Jest runs CommonJS by default. Use --experimental-vm-modules for native ESM, or transform with babel-jest/ts-jest.

ReferenceError: document is not defined

Install jest-environment-jsdom and set testEnvironment: 'jsdom' for browser code.

Jest did not exit one second after the test run has completed

Open handles (DB connections, servers, timers). Close them in afterAll; find them with --detectOpenHandles.

Tests pass alone but fail together

Shared state leaks between tests. Reset mocks (jest.resetAllMocks()) and data in beforeEach.

Snapshot test fails after an intended change

Review the diff, then update with npx jest -u – never update blindly.

Best practices

  • Test behaviour, not implementation details.
  • Keep unit tests fast and isolated; mock the network.
  • One clear assertion focus per test, descriptive names.
  • Run tests in CI on every pull request.
  • Use a separate test database for integration tests.