Testing JavaScript
The "Your First Tests" lesson introduced node:test and assert. This lesson goes further: how to structure a good test, how to organize many tests with describe and setup hooks, how to test asynchronous code and errors properly, how to focus on or skip tests while working, and how to measure coverage. Everything here uses only what's built into Node.js 26, and the same ideas apply to other test runners such as Vitest and Jest.
In One Minute
- Every test follows arrange, act, assert: set up data, run the code, check the result.
- Group related tests with
describe; share setup withbeforeEach,afterEach,before,after. - Make test functions
asyncandawaitthe code; useassert.rejectsfor failing promises. - Test behavior (inputs and outputs), not internal details; one reason to fail per test.
node --test --experimental-test-coveragereports which lines your tests ran.
Anatomy of a Good Test
import { test } from "node:test";
import assert from "node:assert/strict";
function applyDiscount(fee, siblings) {
const rate = siblings >= 2 ? 0.15 : siblings === 1 ? 0.1 : 0;
return Math.round(fee * (1 - rate) * 100) / 100;
}
test("one sibling gives 10% off", () => {
// Arrange
const fee = 450;
const siblings = 1;
// Act
const result = applyDiscount(fee, siblings);
// Assert
assert.equal(result, 405);
});✔ one sibling gives 10% off (0.228417ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2.13075| Part | Contains | Tip |
|---|---|---|
| Arrange | Inputs, fake data, configured objects | Use the smallest data that shows the behavior |
| Act | One call to the code under test | If you need several, maybe you need several tests |
| Assert | Checks on the result | Check what matters to callers, not internals |
A good test name describes the behavior as a sentence ("one sibling gives 10% off"), so a failure report reads like a broken rule.
Organizing with describe and Hooks
describe groups related tests (also called a suite); it is an alias for test that reads naturally inside it. Hooks run setup and cleanup:
| Hook | Runs |
|---|---|
before(fn) | Once, before all tests in the suite |
beforeEach(fn) | Before every test in the suite |
afterEach(fn) | After every test, even failed ones |
after(fn) | Once, after all tests |
import { describe, it, beforeEach } from "node:test";
import assert from "node:assert/strict";
class Ledger {
#payments = [];
add(name, amount) {
if (!(amount > 0)) throw new RangeError("amount must be positive");
this.#payments.push({ name, amount });
}
totalFor(name) {
return this.#payments.filter((p) => p.name === name).reduce((s, p) => s + p.amount, 0);
}
}
describe("Ledger", () => {
let ledger;
beforeEach(() => {
ledger = new Ledger();
ledger.add("Navika", 120);
});
describe("totalFor", () => {
it("sums one student's payments", () => {
ledger.add("Navika", 60);
assert.equal(ledger.totalFor("Navika"), 180);
});
it("returns 0 for a student with no payments", () => {
assert.equal(ledger.totalFor("Zoe"), 0);
});
});
describe("add", () => {
it("rejects non-positive amounts", () => {
assert.throws(() => ledger.add("Navika", 0), { name: "RangeError", message: /positive/ });
});
});
});▶ Ledger
▶ totalFor
✔ sums one student's payments (0.525083ms)
✔ returns 0 for a student with no payments (0.077375ms)
✔ totalFor (0.897917ms)
▶ add
✔ rejects non-positive amounts (0.203375ms)
✔ add (0.257959ms)
✔ Ledger (1.299209ms)
ℹ tests 3
ℹ suites 3
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 3.187beforeEach gives every test a fresh ledger, so tests can't affect each other through shared state, and they pass in any order. The object passed to assert.throws checks the error's name and matches its message against a regular expression.
Assertions in Depth
| Assertion | Passes when |
|---|---|
equal(a, b) / notEqual | a === b (strict mode) |
deepEqual(a, b) / notDeepEqual | Same structure and values (objects, arrays, Maps, Sets, Dates) |
ok(value) | Truthy |
match(string, regex) / doesNotMatch | The string matches |
throws(fn, expected) / doesNotThrow | fn throws an error matching expected |
rejects(promise, expected) / doesNotReject | The promise rejects as expected |
partialDeepStrictEqual(actual, expected) | actual contains at least the properties in expected |
expected can be an error class (RangeError), a regular expression for the message, an object of properties to compare, or a validation function.
Testing Asynchronous Code
Make the test function async and await the code; the runner waits for the returned promise. Expected rejections use await assert.rejects(...):
import { test } from "node:test";
import assert from "node:assert/strict";
async function loadBalance(id, db) {
const student = await db.find(id);
if (!student) throw new Error(`No student ${id}`);
return student.fee - student.paid;
}
const fakeDb = { find: async (id) => (id === 1 ? { fee: 450, paid: 350 } : null) };
test("computes the balance for a known student", async () => {
assert.equal(await loadBalance(1, fakeDb), 100);
});
test("rejects for an unknown student", async () => {
await assert.rejects(loadBalance(9, fakeDb), { message: "No student 9" });
});✔ computes the balance for a known student (0.239417ms)
✔ rejects for an unknown student (0.172209ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2.451Table-Driven Tests
When many inputs share one rule, list them in a table and loop. Each case becomes its own named test, so a failure points to the exact input:
import { describe, it } from "node:test";
import assert from "node:assert/strict";
const lateFee = (days) => Math.min(Math.max(days - 10, 0) * 2, 30);
describe("lateFee", () => {
const cases = [
{ days: 0, fee: 0 },
{ days: 10, fee: 0 },
{ days: 11, fee: 2 },
{ days: 25, fee: 30 },
{ days: 365, fee: 30 },
];
for (const { days, fee } of cases) {
it(`${days} days late costs $${fee}`, () => assert.equal(lateFee(days), fee));
}
});▶ lateFee
✔ 0 days late costs $0 (0.220541ms)
✔ 10 days late costs $0 (0.034292ms)
✔ 11 days late costs $2 (0.02825ms)
✔ 25 days late costs $30 (0.050625ms)
✔ 365 days late costs $30 (0.038583ms)
✔ lateFee (1.018041ms)
ℹ tests 5
ℹ suites 1
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2.845083Focusing, Skipping and Planning
| Option | Use |
|---|---|
test.skip("name", fn) or { skip: "reason" } | Temporarily skip a test (reported as skipped) |
test.todo("name") | A test you plan to write |
test.only(...) with node --test --test-only | Run only the tests you're working on |
node --test --test-name-pattern="lateFee" | Run tests whose names match |
node --test --watch | Rerun on every save |
{ timeout: 1000 } | Fail a test that runs too long |
Never commit .only: CI would silently run a fraction of your tests.
Coverage
Code coverage reports which lines, branches and functions your tests executed:
node --test --experimental-test-coverageThe report lists each file with line, branch and function percentages, and the uncovered line numbers. Coverage finds untested code; it can't prove code is well tested (a line can run without any assertion checking its result). Aim for high coverage of business logic, and look at uncovered branches as questions: "what should happen here, and is there a test?"
What to Test
| Test | Example |
|---|---|
| The normal case | A typical payment |
| Boundaries | 0, exactly the limit, one past it |
| Empty and missing input | [], "", null, undefined |
| Invalid input | Negative, NaN, wrong type |
| Errors | The right error type and message |
| Every bug you fix | A test that failed before the fix (a regression test) |
In Practice
The Fee Tracker's invoice module with a complete test suite: table-driven calculations, error cases, an async loader with a fake, and fresh state per test:
import { describe, it, beforeEach } from "node:test";
import assert from "node:assert/strict";
const TAX = 0.0825;
function invoiceTotal(lines) {
if (!Array.isArray(lines) || lines.length === 0) throw new TypeError("an invoice needs at least one line");
const subtotal = lines.reduce((s, l) => s + l.amount, 0);
return { subtotal, tax: Math.round(subtotal * TAX * 100) / 100, total: Math.round(subtotal * (1 + TAX) * 100) / 100 };
}
async function loadInvoice(id, api) {
const lines = await api.lines(id);
return { id, ...invoiceTotal(lines) };
}
describe("invoiceTotal", () => {
it("adds 8.25% tax", () => {
assert.deepEqual(invoiceTotal([{ amount: 85 }, { amount: 45 }]), { subtotal: 130, tax: 10.73, total: 140.73 });
});
it("rejects empty invoices", () => {
assert.throws(() => invoiceTotal([]), TypeError);
});
});
describe("loadInvoice", () => {
let api;
beforeEach(() => {
api = { lines: async (id) => (id === 7 ? [{ amount: 100 }] : []) };
});
it("loads and totals an invoice", async () => {
assert.deepEqual(await loadInvoice(7, api), { id: 7, subtotal: 100, tax: 8.25, total: 108.25 });
});
it("rejects an invoice with no lines", async () => {
await assert.rejects(loadInvoice(8, api), /at least one line/);
});
});▶ invoiceTotal
✔ adds 8.25% tax (0.361917ms)
✔ rejects empty invoices (0.126542ms)
✔ invoiceTotal (1.065583ms)
▶ loadInvoice
✔ loads and totals an invoice (0.15525ms)
✔ rejects an invoice with no lines (0.092375ms)
✔ loadInvoice (0.325625ms)
ℹ tests 4
ℹ suites 2
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 3.402375Common Mistakes
Tests that depend on each other. Shared state makes order matter. Create fresh data in beforeEach.
Missing await in async tests. The test passes without checking. Await everything.
Testing private details. Tests break on every refactor. Test public behavior.
Committing test.only. Most tests silently stop running in CI.
Chasing 100% coverage. Coverage shows what ran, not what was checked. Focus on meaningful cases.
Practice
Challenge: Write a describe block for formatUsd(cents) with table-driven tests for 0, 5, 12050 and 123456789 cents.
Show solution
import { describe, it } from "node:test";
import assert from "node:assert/strict";
const formatUsd = (cents) => new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(cents / 100);
describe("formatUsd", () => {
for (const [cents, expected] of [[0, "$0.00"], [5, "$0.05"], [12050, "$120.50"], [123456789, "$1,234,567.89"]]) {
it(`formats ${cents} cents as ${expected}`, () => assert.equal(formatUsd(cents), expected));
}
});▶ formatUsd
✔ formats 0 cents as $0.00 (5.914083ms)
✔ formats 5 cents as $0.05 (0.060291ms)
✔ formats 12050 cents as $120.50 (0.0445ms)
✔ formats 123456789 cents as $1,234,567.89 (0.34675ms)
✔ formatUsd (6.746458ms)
ℹ tests 4
ℹ suites 1
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 8.559292
✓ 6 example(s) checked with Node.js v26.13.1, 0 failedKey Takeaways
| Task | Code |
|---|---|
| Group tests | describe("Ledger", () => { ... }) |
| Fresh state | beforeEach(() => { ... }) |
| Expected error | assert.throws(fn, RangeError) |
| Expected rejection | await assert.rejects(promise, /message/) |
| Run with coverage | node --test --experimental-test-coverage |
| Watch | node --test --watch |
Was this tutorial helpful?