Testing Intro

Node has a built-in test runner for automated tests.

Syntaxnode --test

Automated tests check that your code works and keeps working as you change it. Modern Node ships with a built-in test runner — no library required.

The pieces

  • test() — defines a test case.
  • assert — checks that a value is what you expect.

Run your tests with node --test. Popular alternatives include Jest and Vitest.

Example

Example · javascript
// math.test.js — run with: node --test
const test = require('node:test');
const assert = require('node:assert');

function add(a, b) { return a + b; }

test('add sums two numbers', () => {
  assert.strictEqual(add(2, 3), 5);
});

When to use it

  • A developer writes Jest unit tests for a pure utility function to verify its output for edge cases before integrating it into the API route.
  • An integration test spins up a real HTTP server with `http.createServer` (or Supertest against an Express app) and asserts on the JSON response without mocking the database.
  • A CI pipeline runs `npm test -- --coverage` and fails the build when line coverage drops below 80%, enforcing the team's quality gate.

More examples

Unit test with Jest

A minimal Jest test file with two test cases for a simple utility function.

Example · js
// sum.js
module.exports = (a, b) => a + b;

// sum.test.js
const sum = require('./sum');

test('adds two numbers', () => {
  expect(sum(2, 3)).toBe(5);
});

test('handles negatives', () => {
  expect(sum(-1, 1)).toBe(0);
});

Mock a module in Jest

Uses `jest.mock` to replace `fs/promises` with a mock that returns a fixed value, isolating the unit under test.

Example · js
jest.mock('fs/promises', () => ({
  readFile: jest.fn().mockResolvedValue('{"port":3000}'),
}));

const { readFile } = require('fs/promises');
const config = require('./config'); // internally calls readFile

test('loads config', async () => {
  const cfg = await config.load();
  expect(cfg.port).toBe(3000);
  expect(readFile).toHaveBeenCalledTimes(1);
});

Node built-in test runner

Uses Node 18+'s built-in `node:test` module and `node:assert` to run tests without installing any test framework.

Example · js
// test/sum.test.mjs  (Node 18+)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import sum from '../src/sum.mjs';

test('adds numbers', () => {
  assert.equal(sum(1, 2), 3);
});

// Run: node --test test/sum.test.mjs

Discussion

  • Be the first to comment on this lesson.