Testing Basics
node:test, assertions, mocking, and testing async code.
Why test, and with what
Tests are small programs that run your code and verify it behaves as expected. They catch regressions the moment you introduce them, document intended behavior, and make refactoring safe.
Since Node 20, everything you need is built in — no packages required:
node:test— the test runner:test(),describe(),it()node:assert— assertions that throw when expectations fail
Run tests with node --test, which automatically discovers files like *.test.js and anything in test/ directories.
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);
});
test("add handles negatives", () => {
assert.strictEqual(add(2, -5), -3);
});
// Run with: node --testAssertions: strict by default
An assertion compares actual and expected values and throws on mismatch — which the runner reports as a failure. The essential ones:
assert.strictEqual(actual, expected)—===comparison for primitivesassert.deepStrictEqual(actual, expected)— recursive comparison for objects and arraysassert.ok(value)— asserts truthinessassert.throws(fn, matcher)— asserts that a function throwsassert.rejects(promise)— the async equivalent of throws
Always prefer the strict variants; the non-strict ones use loose == semantics that hide type bugs.
const assert = require("node:assert");
assert.strictEqual(2 + 2, 4);
assert.deepStrictEqual({ a: 1, list: [2, 3] }, { a: 1, list: [2, 3] });
assert.ok("non-empty strings are truthy");
assert.throws(
() => JSON.parse("{bad json"),
SyntaxError
);
// A failed assertion throws an AssertionError:
try {
assert.strictEqual(1, 2);
} catch (err) {
console.log("failure message:", err.message);
}
console.log("all other assertions passed");Organizing and testing async code
describe() groups related tests; it() is a synonym for test() that reads nicely inside groups. For async code the rule is simple: make the test function async and await inside it. The runner waits for the returned promise; a rejection fails the test.
Test names should state behavior — "returns 404 for a missing user" beats "test2" — because names are what you read when things break.
const { describe, it } = require("node:test");
const assert = require("node:assert");
async function fetchUser(id) {
if (id <= 0) throw new Error("invalid id");
return { id, name: "User " + id };
}
describe("fetchUser", () => {
it("returns the user for a valid id", async () => {
const user = await fetchUser(7);
assert.deepStrictEqual(user, { id: 7, name: "User 7" });
});
it("rejects for an invalid id", async () => {
await assert.rejects(fetchUser(-1), /invalid id/);
});
});Mocking: isolating the code under test
Real code calls databases, APIs, and clocks — things you don't want in a unit test. A mock stands in for a dependency, letting you control its behavior and inspect how it was called.
node:test ships a mocking toolkit:
mock.fn(impl?)— a trackable function;fn.mock.callsrecords every invocationmock.method(obj, "name", impl)— temporarily replace a methodmock.timers— fakesetTimeout/Dateso time-based code tests instantly
Designing code to *receive* its dependencies (dependency injection) instead of hard-coding them is what makes mocking easy.
const { test, mock } = require("node:test");
const assert = require("node:assert");
// Code under test receives its dependency:
async function notifyAll(users, sendEmail) {
for (const user of users) await sendEmail(user.email, "Welcome!");
}
test("emails every user", async () => {
const sendEmail = mock.fn(async () => true);
await notifyAll(
[{ email: "a@x.com" }, { email: "b@x.com" }],
sendEmail
);
assert.strictEqual(sendEmail.mock.calls.length, 2);
assert.strictEqual(sendEmail.mock.calls[0].arguments[0], "a@x.com");
});What to test, and the AAA pattern
Structure every test as Arrange, Act, Assert: set up inputs, run the code, check the result. One behavior per test — when it fails, you know exactly what broke.
Spend your testing budget wisely:
- Do test core logic, edge cases (empty input, zero, huge values), and error paths
- Do test the bug you just fixed — that test prevents its return forever
- Don't test framework internals or trivial getters
- Don't chase 100% coverage for its own sake; coverage measures execution, not correctness
Wire node --test into your package.json test script and run it in CI on every push — tests that don't run are decoration.
const assert = require("node:assert");
function applyDiscount(cart, percent) {
if (percent < 0 || percent > 100) throw new Error("bad percent");
const total = cart.reduce((sum, item) => sum + item.price, 0);
return total * (1 - percent / 100);
}
// Arrange
const cart = [{ price: 40 }, { price: 60 }];
// Act
const total = applyDiscount(cart, 25);
// Assert
assert.strictEqual(total, 75);
console.log("pass: 25% off 100 is", total);
// And the error path:
assert.throws(() => applyDiscount(cart, 150), /bad percent/);
console.log("pass: invalid percent throws");Check your understanding
5 questionsQuestion 1 of 5
Score: 0