Testing with node:test

Topic 1 of 3 in Testing7 min readIntermediateFree course

Overview

Every time you change code, you risk breaking something that used to work. Clicking through your API by hand after every change is slow and you’ll inevitably miss things. Automated tests are small programs that check your code does what it should — in seconds, every time, on every machine.

Node.js has a built-in test runner (node:test) and assertion library (node:assert). You don’t need to install Jest, Mocha or Vitest to write good tests — though those are fine choices too, and the ideas carry over directly.

The testing pyramid. At the base, many fast unit tests of pure functions and services with fakes. In the middle, integration or API tests that send HTTP requests to the app with a test database. At the top, a few slow end-to-end tests with a real browser and deployed API. For APIs, integration tests through HTTP give the best confidence per test.

This topic covers the tools; the next two cover testing HTTP APIs and replacing dependencies with fakes.

Your first test

JavaScript
// src/money.js
export function formatRupees(paise) {
  return `₹${(paise / 100).toFixed(2)}`;
}
JavaScript
// src/money.test.js
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { formatRupees } from './money.js';

test('formats paise as rupees with two decimals', () => {
  assert.equal(formatRupees(49900), '₹499.00');
});

test('handles zero', () => {
  assert.equal(formatRupees(0), '₹0.00');
});
Terminal
node --test
Text
✔ formats paise as rupees with two decimals (0.6ms)
✔ handles zero (0.1ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

With no arguments, node --test finds files named like *.test.js, *-test.js, *_test.js and files inside test/ folders. Pass a glob to choose: node --test "src/**/*.test.js".

Add it to package.json so npm test works everywhere:

JSON
{ "scripts": { "test": "node --test", "test:watch": "node --test --watch" } }

Assertions

Import the strict variant — it compares with === and checks types, avoiding surprising coercions:

JavaScript
import assert from 'node:assert/strict';

assert.equal(actual, expected);            // ===
assert.notEqual(a, b);
assert.deepEqual({ a: [1, 2] }, { a: [1, 2] }); // compares contents of objects and arrays
assert.ok(value);                          // truthy
assert.match('Hello, Asha', /Asha/);
assert.throws(() => parseAge('abc'), { name: 'RangeError' });
await assert.rejects(loadUser(999), { status: 404 });

When an assertion fails, the test fails with a clear diff of expected versus actual values.

Grouping with describe and it

describe groups related tests; it is an alias of test that reads nicely inside it:

JavaScript
import { describe, it } from 'node:test';

describe('cart totals', () => {
  it('is zero for an empty cart', () => {
    assert.equal(total([]), 0);
  });

  it('adds item prices times quantities', () => {
    assert.equal(total([{ price: 100, qty: 2 }, { price: 50, qty: 1 }]), 250);
  });

  describe('with a discount code', () => {
    it('subtracts the percentage', () => { /* … */ });
    it('never goes below zero', () => { /* … */ });
  });
});

Async tests

Make the test function async and await inside it. The test fails if the promise rejects:

JavaScript
it('loads a saved settings file', async () => {
  const settings = await loadSettings('test/fixtures/settings.json');
  assert.equal(settings.theme, 'dark');
});

Hooks

Hooks set up and tear down state shared by several tests:

JavaScript
import { describe, it, before, beforeEach, afterEach, after } from 'node:test';

describe('users repository', () => {
  before(async () => { await migrateTestDatabase(); });     // once, before all
  beforeEach(async () => { await truncateTables(); });     // before every test
  after(async () => { await pool.end(); });                // once, after all

  it('inserts a user', async () => { /* … */ });
  it('rejects duplicate emails', async () => { /* … */ });
});

Each test should start from a known state and not depend on the order tests run in — that’s what beforeEach is for.

Useful options

JavaScript
it.skip('not ready yet', () => {});
it.todo('handles leap years');
it.only('focus on this one', () => {});   // run with: node --test --test-only
Terminal
node --test --test-name-pattern="cart"    # run matching tests only
node --test --watch                       # re-run on save
node --test --experimental-test-coverage  # show which lines were tested
node --test --test-reporter=spec          # choose an output format (tap, dot, junit…)

Coverage reports show untested code, but high coverage isn’t the goal — confidence is. One good test of an important rule beats five tests of trivial getters.

Writing good tests

  • Test behaviour, not implementation. Call public functions and check results; don’t reach into private details. Then you can refactor freely.
  • One idea per test, named as a sentence: it('rejects passwords shorter than 12 characters'). When it fails, the name tells you what broke.
  • Arrange, act, assert — set up the data, do one thing, check the outcome.
  • Cover the edges: empty input, zero, maximum values, invalid types, error paths.
  • Keep tests fast. Slow suites get skipped. Use fakes for slow dependencies in unit tests (see Mocking and test doubles).
  • Write a failing test for every bug before fixing it, so it can never come back unnoticed.

Run tests in CI

Tests only protect you if they run. A continuous-integration service such as GitHub Actions runs npm test on every push and pull request:

YAML
# .github/workflows/test.yml
name: test
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version-file: .nvmrc, cache: npm }
      - run: npm ci
      - run: npm test

Now a pull request that breaks something shows a red ✗ before anyone merges it.

Start small. One test file for your most important business rules is infinitely better than none. Add tests whenever you touch code, and especially whenever you fix a bug.

Exercise

Test a slug function

Write tests in slugify.test.js for a slugify(text) function: it lower-cases, trims, replaces runs of non-alphanumeric characters with a single dash, and removes leading/trailing dashes. Cover normal text, extra spaces, punctuation, an empty string, and that it throws a TypeError for non-strings.

JavaScript
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { slugify } from './slugify.js';

describe('slugify', () => {
  // your tests here
});

Summary

  • Automated tests let you change code with confidence and catch regressions before users do.
  • node --test finds and runs test files; describe/it (or test) come from node:test.
  • Use node:assert/strict: equal, deepEqual, throws, rejects, match.
  • Hooks (before, beforeEach, afterEach, after) set up and clean up shared state.
  • Test behaviour through public functions, one idea per test, with descriptive names.