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 need | Version / notes |
|---|---|
| Node.js | Current LTS release |
| A JavaScript/TypeScript project | With code you want to test |
| Editor | VS Code with the Jest extension (optional) |
3. Local setup
1Install Jest
Add it as a dev dependency and a test script.
BASHnpm install --save-dev jest npm pkg set scripts.test="jest"2ES modules or TypeScript?
For
import/exportwithout 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
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'); }); });2Mock a dependency
jest.fn()records calls; mocks keep tests fast and independent of networks or databases.JStest('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' })); });3Test an Express API with supertest
Export the
appwithout callinglistenso tests can use it directly.JSnpm 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' }); });4Run tests and coverage
Watch mode re-runs related tests on save.
BASHnpm 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.
NODE_ENV=test
DATABASE_URL=postgres://test:test@localhost:5432/app_test
PAYMENT_API_URL=http://localhost:4010 # mock serverKey dependencies
| Package / tool | Used for |
|---|---|
jest | Runner, expect, mocks, coverage |
ts-jest / babel-jest | TypeScript / transpilation |
jest-environment-jsdom | Browser-like environment for DOM/React tests |
@testing-library/react | User-centric component tests |
supertest | HTTP assertions against Express apps |
Folder structure
project/
├── src/
│ ├── price.js
│ └── price.test.js # tests next to code
├── test/
│ └── api.test.js # integration tests
├── jest.config.js
└── coverage/ # generated reportEssential commands
| Command | What it does |
|---|---|
npx jest | Run all tests |
npx jest --watch | Re-run on changes |
npx jest path/to/file | Run one file |
npx jest -t "name" | Run tests matching a name |
npx jest --coverage | Coverage report in coverage/ |
npx jest --ci | CI 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
| Requirement | Recommendation |
|---|---|
| CI runner | GitHub Actions / GitLab CI / Jenkins with the same Node.js version as development |
| Install | npm ci from the lockfile |
| Gate | Test job marked as a required check before merge/deploy |
| Reports | JUnit XML / HTML / coverage uploaded as artifacts |
Deployment steps
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' }]], };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.ymlname: 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 --coverage3Keep 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/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.
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.