Your First Tests
A test is a small piece of code that runs your code with a known input and checks that the output is what you expect. Instead of re-checking by hand every time you change something, you run the tests and see in seconds whether everything still works. Node.js has a complete test runner built in, node:test, with an assertion library, node:assert, so you can write real tests with no packages to install. From this lesson on, every checkpoint in the course includes tests.
In One Minute
- A test arranges an input, calls the code, and asserts the result: "
lateFee(14)should be8". import { test } from "node:test"andimport assert from "node:assert/strict", thentest("name", () => { ... }).assert.equal(actual, expected)for primitives,assert.deepEqualfor objects and arrays,assert.throwsfor errors.- Run tests with
node --test(finds test files) ornode file.test.js. - Test the normal case, the edge cases (zero, empty, boundaries) and the error cases.
Why Write Tests
| Without tests | With tests |
|---|---|
| You check by hand after every change, and skip it when busy | node --test checks everything in seconds |
| A fix in one place silently breaks another | The broken test points at it immediately |
| You're afraid to clean up messy code | Tests prove the cleanup didn't change behavior |
| "It worked on my machine" | The test is a precise, repeatable description of "working" |
Tests also document your code: test("no late fee during the 10-day grace period", ...) explains a rule better than a comment.
A First Check with console.assert
The simplest check is console.assert(condition, message), which prints only when the condition is false:
function lateFee(daysLate) {
return Math.max(daysLate - 10, 0) * 2;
}
console.assert(lateFee(14) === 8, "14 days late should cost $8");
console.assert(lateFee(5) === 0, "inside the grace period should be free");
console.assert(lateFee(10) === 2, "exactly 10 days late");
console.log("Checks finished");Assertion failed: exactly 10 days late
Checks finishedThe third check is wrong on purpose: 10 days late is still inside the grace period, so the real answer is 0, not 2. console.assert printed one line for it, and then the program carried on to "Checks finished" as if all were well. In a browser, that line goes to the DevTools console (in red), where it is easy to miss; in Node.js it goes to the error stream. Nothing counts the failures or stops the program. Real tests fix all of that.
Writing Tests with node:test
Syntax
import { test } from "node:test";
import assert from "node:assert/strict";
test("description of the behavior", () => {
assert.equal(actual, expected);
});Import from node:assert/strict, which makes equal use === and deepEqual compare types strictly. (Plain node:assert uses the loose == rules for its legacy methods.)
Example
Here is the late fee function with real tests. Put the function and tests in one file for now; the In Practice section shows the usual two-file layout.
import { test } from "node:test";
import assert from "node:assert/strict";
function lateFee(daysLate) {
if (!Number.isInteger(daysLate) || daysLate < 0) {
throw new RangeError(`daysLate must be a whole number >= 0, got ${daysLate}`);
}
return Math.min(Math.max(daysLate - 10, 0) * 2, 30);
}
test("no fee during the 10-day grace period", () => {
assert.equal(lateFee(0), 0);
assert.equal(lateFee(10), 0);
});
test("$2 per day after the grace period", () => {
assert.equal(lateFee(11), 2);
assert.equal(lateFee(14), 8);
});
test("capped at $30", () => {
assert.equal(lateFee(25), 30);
assert.equal(lateFee(365), 30);
});
test("rejects invalid input", () => {
assert.throws(() => lateFee(-1), RangeError);
assert.throws(() => lateFee(2.5), { name: "RangeError" });
});✔ no fee during the 10-day grace period (0.2525ms)
✔ $2 per day after the grace period (0.041291ms)
✔ capped at $30 (0.033708ms)
✔ rejects invalid input (0.161875ms)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2.725083Each test gets a description and a function. Each test is marked with a check mark when it passes or a cross when it fails, and the summary counts them. The durations change on every run, so this output isn't compared word for word when the lesson is checked. (Try it can't run node:test, which only exists in Node.js; run it in a terminal with Node.js 26.)
The Main Assertions
| Assertion | Passes when |
|---|---|
assert.equal(a, b) | a === b (with node:assert/strict) |
assert.notEqual(a, b) | a !== b |
assert.deepEqual(a, b) | Objects or arrays have the same structure and values |
assert.ok(value) | value is truthy |
assert.throws(fn, expected) | Calling fn throws an error matching expected (a class, a regex, or an object of properties) |
assert.rejects(promise, expected) | A promise rejects (async chapter) |
assert.match(string, regex) | The string matches the pattern |
equal versus deepEqual matters for objects: two different objects with the same contents are not ===, so equal fails and deepEqual passes.
import { test } from "node:test";
import assert from "node:assert/strict";
const summarize = (payments) => ({
count: payments.length,
total: payments.reduce((s, p) => s + p, 0),
});
test("summarize counts and totals", () => {
assert.deepEqual(summarize([120, 85]), { count: 2, total: 205 });
assert.deepEqual(summarize([]), { count: 0, total: 0 });
});✔ summarize counts and totals (0.398667ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2.299792Reading a Failing Test
When an assertion fails, the runner shows what it expected, what it got, and where:
✖ $2 per day after the grace period (1.2ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
10 !== 8
at TestContext.<anonymous> (file:///fee-tracker/late-fee.test.js:17:10)
...
ℹ tests 4
ℹ pass 3
ℹ fail 1Read it in three parts: which test (its description), the difference (actual !== expected: the function returned 10, the test expected 8), and where (line 17 of the test file). Then decide which is wrong: the code, or the test's expectation. Both happen.
What to Test
For each function, test three kinds of input:
| Kind | Examples for lateFee |
|---|---|
| Normal cases | 14 days, 20 days |
| Edge cases | 0, exactly 10 (the boundary), 11 (just past it), exactly where the cap starts |
| Error cases | Negative numbers, decimals, undefined |
Bugs cluster at boundaries: "more than 10 days" versus "10 or more" is a one-character difference (> versus >=) that only a test at exactly 10 catches.
In Practice
Real projects keep code and tests in separate files. The Fee Tracker's money helpers live in money.js, exported as a module, and money.test.js imports and tests them:
export function toCents(dollars) {
if (!Number.isFinite(dollars)) throw new TypeError(`Not a number: ${dollars}`);
return Math.round(dollars * 100);
}
export function formatCents(cents) {
return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(cents / 100);
} import { test } from "node:test";
import assert from "node:assert/strict";
import { toCents, formatCents } from "./money.mjs";
test("toCents avoids floating-point errors", () => {
assert.equal(toCents(1.15), 115);
assert.equal(toCents(0.1 + 0.2), 30);
});
test("toCents rejects non-numbers", () => {
assert.throws(() => toCents(Number("abc")), TypeError);
});
test("formatCents shows US dollars", () => {
assert.equal(formatCents(123450), "$1,234.50");
assert.equal(formatCents(0), "$0.00");
});✔ toCents avoids floating-point errors (0.362708ms)
✔ toCents rejects non-numbers (0.14ms)
✔ formatCents shows US dollars (5.970791ms)
ℹ tests 3
ℹ suites 0
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 9.099667In your own project, name the files money.js and money.test.js with "type": "module" in package.json, and import "./money.js". (The import above says ./money.mjs only because this site's checker saves module examples with the .mjs extension.) Then run every test file in the project with:
node --testnode --test finds files named like *.test.js, *-test.js and test/*.js. Add --watch to rerun on every save. The testing lessons later in the course cover grouping with describe, setup with beforeEach, mocking, coverage and async tests.
Common Mistakes
Testing only the happy path. Bugs live at boundaries and in bad input. Test 0, empty, exactly-at-the-limit and invalid values.
Using equal for objects. Different objects are never ===. Use deepEqual.
Importing from node:assert instead of node:assert/strict. The legacy equal uses ==, so assert.equal(1, "1") passes. Use the strict version.
Tests that depend on each other or on the current date. Each test should set up its own data, and use fixed dates.
Practice
Challenge: Write tests for this discount(fee, siblings) function: 0 siblings gives no discount, 1 sibling gives 10%, 2 or more give 15%, and a negative fee throws a RangeError.
Show solution
import { test } from "node:test";
import assert from "node:assert/strict";
function discount(fee, siblings) {
if (fee < 0) throw new RangeError("fee must not be negative");
const rate = siblings >= 2 ? 0.15 : siblings === 1 ? 0.1 : 0;
return Math.round(fee * rate * 100) / 100;
}
test("no siblings, no discount", () => assert.equal(discount(450, 0), 0));
test("one sibling, 10%", () => assert.equal(discount(450, 1), 45));
test("two or more siblings, 15%", () => {
assert.equal(discount(450, 2), 67.5);
assert.equal(discount(450, 5), 67.5);
});
test("negative fee throws", () => assert.throws(() => discount(-1, 0), RangeError));✔ no siblings, no discount (0.242958ms)
✔ one sibling, 10% (0.054083ms)
✔ two or more siblings, 15% (0.036459ms)
✔ negative fee throws (0.114333ms)
ℹ tests 4
ℹ suites 0
ℹ pass 4
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2.624458Key Takeaways
| Task | Code |
|---|---|
| Import | import { test } from "node:test"; import assert from "node:assert/strict"; |
| A test | test("rule", () => { ... }) |
| Compare values | assert.equal(actual, expected) |
| Compare objects | assert.deepEqual(actual, expected) |
| Expect an error | assert.throws(() => fn(), RangeError) |
| Run all tests | node --test |
Was this tutorial helpful?