Unit Testing with node:test
Write focused tests for pure and async JavaScript using Node's built-in test runner.
By the end, you’ll be able to…
- Structure a test with the arrange, act, assert pattern.
- Use node:test and node:assert/strict to verify values and errors.
- Isolate tests with fresh state, fakes, and injected dependencies.
01Why tests earn their keep
A test is a small program that calls your code with known inputs and checks the result. Its immediate output is a pass or fail, but its real value arrives months later, when an unrelated change breaks a quiet assumption. A named test also documents the behaviour your team expects, in a form that cannot drift out of date unnoticed.
Tests are not free. Every assertion must be maintained, and a brittle suite can slow change more than it protects it. Spend effort on behaviour with consequences: money calculations, validation boundaries, permission checks, and data parsing. Testing every private helper ties the suite to today's implementation and makes harmless refactors expensive.
02Arrange, act, assert
Most useful tests follow three beats. Arrange the inputs and dependencies, act by performing one operation, then assert the observable result. Keeping those phases visible makes a failure easier to diagnose: you can see what went in, what ran, and what came back. If a test needs several actions, it is usually testing several behaviours.
Name tests after behaviour rather than function names. Rejecting a discount above one hundred percent explains intent; testing applyDiscount call three does not. Prefer one meaningful assertion per behaviour. A test that checks six unrelated facts stops at the first failure and hides the rest, which turns diagnosis into guesswork.
03The built-in test runner
Node.js ships a test runner in the node:test module, so a small project needs no test framework dependency. Run node --test from the project root; Node discovers files named *.test.js, *-test.js, or files under a test directory. The runner executes each file in its own process, reports durations, and exits with a failing status when any test fails.
Assertions come from node:assert/strict. Use assert.equal for primitives, assert.deepEqual for object and array structure, assert.throws for synchronous errors, and assert.rejects for promises that should fail. The strict variant uses strict equality, which avoids surprising coercions such as treating the string zero as equal to the number zero.
04Async tests and isolation
An async test must return or await its work. Mark the callback async and await every promise before asserting; otherwise the test can pass before the operation finishes. assert.rejects takes a promise or an async function and can also check the error message, which keeps failure tests specific.
Tests should not depend on execution order or leftover state. Create a fresh object inside each test instead of sharing a module-level array. Node may run test files concurrently, and even within a file a mutation from one test can make the next one pass for the wrong reason. Isolation turns a failure into a fact about one behaviour.
05Fakes, seams, and coverage
A fake is a small stand-in for a dependency such as a clock, network client, or repository. Dependency injection creates a seam: pass the dependency into the function instead of importing a concrete singleton. A hand-written fake is often clearer than a large mocking library, because it exposes only the methods the test needs and returns predictable data.
Coverage reports which lines and branches executed. They are useful for finding untested error paths, not for proving correctness. A line can run without its result being checked, and a suite can assert the wrong thing at full coverage. Treat a coverage drop as a question, then decide whether the missing behaviour deserves a test.
The ideas worth keeping.
- Test observable behaviour with clear arrange, act, and assert phases.
- node:test and node:assert/strict provide a dependency-free foundation for unit tests.
- Fresh state, async awareness, and injected fakes keep tests reliable and fast.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Test a cart total
Given a totalCents(items) function that sums priceCents times quantity, write two node:test cases: an empty cart returns 0, and a cart with two notebook lines at 250 cents for 2 and 99 cents for 3 returns 797.
Explore a worked solution
import test from 'node:test';import assert from 'node:assert/strict';import { totalCents } from './cart.js';test('returns zero for an empty cart', () => { assert.equal(totalCents([]), 0);});test('adds price times quantity for every line', () => { const cart = [ { priceCents: 250, quantity: 2 }, { priceCents: 99, quantity: 3 }, ]; assert.equal(totalCents(cart), 797);});The first test pins the identity case that a reduce with an initial value should handle. The second checks the actual multiplication and addition; 500 plus 297 is 797, so a wrong quantity or price fails clearly.
Exercise 2: Prove a failure stops the save
Using the syncTasks function from this lesson, write a test where fetchTasks throws Network down. Assert that the returned promise rejects with that message and that saveTasks was never called.
Explore a worked solution
import test from 'node:test';import assert from 'node:assert/strict';import { syncTasks } from './sync.js';test('does not save when fetching fails', async () => { const saved = []; await assert.rejects( () => syncTasks({ fetchTasks: async () => { throw new Error('Network down'); }, saveTasks: async (tasks) => saved.push(...tasks), }), /Network down/, ); assert.equal(saved.length, 0);});assert.rejects awaits the promise and checks the failure, so the test cannot finish early. The saved array is local to this test, and its emptiness proves that the second dependency never ran.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Exercise 1: Test a cart total
Given a totalCents(items) function that sums priceCents times quantity, write two node:test cases: an empty cart returns 0, and a cart with two notebook lines at 250 cents for 2 and 99 cents for 3 returns 797.
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.