Your First Tests

Updated · 9 min read
mediumES2026javascripttestingnode-testassert

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 be 8".
  • import { test } from "node:test" and import assert from "node:assert/strict", then test("name", () => { ... }).
  • assert.equal(actual, expected) for primitives, assert.deepEqual for objects and arrays, assert.throws for errors.
  • Run tests with node --test (finds test files) or node file.test.js.
  • Test the normal case, the edge cases (zero, empty, boundaries) and the error cases.

Why Write Tests

Without testsWith tests
You check by hand after every change, and skip it when busynode --test checks everything in seconds
A fix in one place silently breaks anotherThe broken test points at it immediately
You're afraid to clean up messy codeTests 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:

assert-console.js▶ Try it
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");
Output
Assertion failed: exactly 10 days late
Checks finished

The 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

syntax.test.js
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.

late-fee.test.js▶ Try it
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" });
});
Output
✔ 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.725083

Each 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

AssertionPasses 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.

deep.test.js▶ Try it
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 });
});
Output
✔ summarize counts and totals (0.398667ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2.299792

Reading a Failing Test

When an assertion fails, the runner shows what it expected, what it got, and where:

Terminal (a failing test)
✖ $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 1

Read 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:

KindExamples for lateFee
Normal cases14 days, 20 days
Edge cases0, exactly 10 (the boundary), 11 (just past it), exactly where the cap starts
Error casesNegative 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:

money.js▶ Try it
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);
}
Output
 
money.test.js▶ Try it
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");
});
Output
✔ 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.099667

In 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:

Terminal
node --test

node --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
discount.test.js▶ Try it
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));
Output
✔ 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.624458

Quick check: First tests

3 questions
1Which assertion should compare two arrays by contents?
2Why test the input 10 for a rule that charges after 10 days?
3What command runs every test file in a project?

Key Takeaways

TaskCode
Importimport { test } from "node:test"; import assert from "node:assert/strict";
A testtest("rule", () => { ... })
Compare valuesassert.equal(actual, expected)
Compare objectsassert.deepEqual(actual, expected)
Expect an errorassert.throws(() => fn(), RangeError)
Run all testsnode --test

Was this tutorial helpful?

Lesson 63 of 139