Testing with node:test
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.
This topic covers the tools; the next two cover testing HTTP APIs and replacing dependencies with fakes.
Your first test
// src/money.js
export function formatRupees(paise) {
return `₹${(paise / 100).toFixed(2)}`;
}// 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');
});node --test✔ formats paise as rupees with two decimals (0.6ms)
✔ handles zero (0.1ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0With 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:
{ "scripts": { "test": "node --test", "test:watch": "node --test --watch" } }Assertions
Import the strict variant — it compares with === and checks types, avoiding surprising coercions:
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:
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:
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:
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
it.skip('not ready yet', () => {});
it.todo('handles leap years');
it.only('focus on this one', () => {}); // run with: node --test --test-onlynode --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:
# .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 testNow 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.
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.
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { slugify } from './slugify.js';
describe('slugify', () => {
// your tests here
});import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { slugify } from './slugify.js';
describe('slugify', () => {
it('lower-cases and joins words with dashes', () => {
assert.equal(slugify('Node JS Course'), 'node-js-course');
});
it('trims and collapses whitespace', () => {
assert.equal(slugify(' lots of space '), 'lots-of-space');
});
it('replaces punctuation', () => {
assert.equal(slugify('Hello, World! (2026)'), 'hello-world-2026');
});
it('returns an empty string for empty input', () => {
assert.equal(slugify(''), '');
});
it('throws for non-strings', () => {
assert.throws(() => slugify(42), TypeError);
});
});
// slugify.js
// export function slugify(text) {
// if (typeof text !== 'string') throw new TypeError('slugify expects a string');
// return text.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
// }Summary
- Automated tests let you change code with confidence and catch regressions before users do.
node --testfinds and runs test files;describe/it(ortest) come fromnode: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.