← Back to Node.js, page 4

nodejs-0061 · Easy fresher

What are the basics of Jest for testing Node.js code, and how does it differ from node:test?

Jest is a test framework with a test runner, expect matchers, mock functions (jest.fn, jest.spyOn), module mocking, fake timers, snapshots and coverage in one package. Tests use describe, test and expect. For Node services set testEnvironment to node. It needs a dependency, while node:test is built in.

Full answer

Jest is the most common JavaScript test framework. Typical file: sum.test.js.

Core API:

  • describe(name, fn) groups tests. test(name, fn) or it(name, fn) defines one.
  • expect(value) with matchers: toBe (Object.is), toEqual (deep, ignores undefined properties), toStrictEqual, toThrow, toContain, toMatchObject, resolves and rejects for promises.
  • Hooks: beforeEach, afterEach, beforeAll, afterAll.
  • jest.fn() creates a mock function with mock.calls and mock.results. jest.spyOn(object, 'method') watches or replaces a method and can be restored. jest.mock('./module') replaces a whole module. jest.useFakeTimers() controls time.
  • Snapshots: expect(value).toMatchSnapshot() compares with a stored file. Good for stable output, bad for large, noisy values.
  • Coverage: jest --coverage.

Configuration: in package.json under "jest", or jest.config.js. For back-end code use { "testEnvironment": "node" }. For ES modules, Jest needs extra setup (--experimental-vm-modules or a transform), which is one reason some teams choose Vitest or node:test.

Compared with node:test: Jest has a bigger feature set (snapshots, powerful module mocks, watch mode with filters) and many examples online, but it adds a large dependency and runs tests in a sandboxed VM context, which can hide real Node behaviour. node:test is smaller, faster to start, and uses real Node modules.

Run with npx jest, or npm test. Use --runInBand to run files serially when tests share a database.

javascript
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'jest-demo-'));
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'jest-demo', jest: { testEnvironment: 'node' } }));

fs.writeFileSync(path.join(dir, 'report.js'), `
exports.average = (marks) => marks.reduce((a, b) => a + b, 0) / marks.length;
exports.publish = async (student, send) => {
  await send(student.email, 'Average: ' + exports.average(student.marks).toFixed(1));
  return 'published';
};
`);

fs.writeFileSync(path.join(dir, 'report.test.js'), `
const { average, publish } = require('./report');

describe('report', () => {
  let send;
  beforeEach(() => { send = jest.fn().mockResolvedValue(undefined); });

  test('average of three marks', () => {
    expect(average([70, 80, 90])).toBe(80);
    expect(average([1, 2])).toBeCloseTo(1.5);
  });

  test('objects use toEqual', () => {
    expect({ name: 'Asha', tags: ['a'] }).toEqual({ name: 'Asha', tags: ['a'] });
  });

  test('publish sends one email', async () => {
    await expect(publish({ email: 'asha@example.com', marks: [70, 80] }, send)).resolves.toBe('published');
    expect(send).toHaveBeenCalledTimes(1);
    expect(send).toHaveBeenCalledWith('asha@example.com', 'Average: 75.0');
  });

  test('spyOn watches an existing method', () => {
    const spy = jest.spyOn(Math, 'max');
    Math.max(1, 2);
    expect(spy).toHaveBeenCalledWith(1, 2);
    spy.mockRestore();
  });

  test('errors are checked with toThrow', () => {
    expect(() => JSON.parse('{bad')).toThrow(SyntaxError);
  });
});
`);

const jestBin = require.resolve('jest/bin/jest');
const run = spawnSync(process.execPath, [jestBin, '--rootDir', dir, '--json', '--silent'], { encoding: 'utf8', cwd: dir });
const result = JSON.parse(run.stdout);
for (const test of result.testResults[0].assertionResults) console.log(test.status.padEnd(7), test.fullName);
console.log('passed:', result.numPassedTests, '| failed:', result.numFailedTests, '| exit code:', run.status);

fs.rmSync(dir, { recursive: true });

The snippet creates a small project in a temporary folder and runs Jest on it with JSON output, so the result is easy to read. Install first with npm install jest (run here with jest 30.5.2). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): passed report average of three marks passed report objects use toEqual passed report publish sends one email passed report spyOn watches an existing method passed report errors are checked with toThrow passed: 5 | failed: 0 | exit code: 0

Key points

  • describe, test and expect are the core.
  • jest.fn, spyOn and jest.mock are the mocking tools.
  • Set testEnvironment to node for server code.
  • Jest has more features. node:test has no extra dependency.

Common mistakes

  • Using toBe for objects and arrays, which compares references.
  • Forgetting await or return in an async test, so it passes too early.
  • Not restoring spies and mocks between tests.
  • Relying on snapshots for large, changing output.

Follow-ups

  • How does jest.mock differ from jest.spyOn?
  • How do you test ES modules with Jest?
  • What is the difference between toEqual and toStrictEqual?

Tips

  • Know toBe vs toEqual cold.
  • Say when you would pick node:test instead, to show judgement.
  • Mention that the node test environment is a setting you must choose.