Testing in Practice

Updated · 11 min read
mediumES2026javascripttestingmocksfake-timersnode-test

Real code talks to the outside world: it calls APIs with fetch, waits with timers, reads the clock, writes to storage, updates the page. Tests can't depend on a real server being up or on waiting 30 real seconds, so they replace those dependencies with test doubles: fakes, stubs and mocks that behave predictably and record how they were used. This lesson shows how to design code so it can be tested this way (dependency injection), how to use node:test's built-in mocking for functions, methods, fetch and timers, how to test DOM code, and how to balance unit, integration and end-to-end tests.

In One Minute

  • Test doubles stand in for real dependencies: a fake works simply (an in-memory database), a stub returns fixed answers, a mock also records calls.
  • Inject dependencies (pass fetch, the clock, storage as parameters) so tests can supply doubles.
  • node:test provides mock.fn(), mock.method(obj, name) and mock.timers (fake setTimeout, Date).
  • Test DOM code with a real or simulated document (jsdom, or a browser runner such as Playwright).
  • Follow the test pyramid: many fast unit tests, fewer integration tests, a few end-to-end tests. Write a test for every bug you fix.

Test Doubles

KindWhat it isExample
FakeA simple working implementationAn in-memory Map instead of a database
StubReturns canned answersasync () => [{ amount: 120 }] instead of an API call
Spy / mockRecords calls (and may return answers) so tests can check how it was usedmock.fn() that records arguments

Design for Testability: Inject Dependencies

Code that reaches out to globals directly is hard to test. Code that receives its dependencies is easy:

injectable.js▶ Try it
async function sendReminders({ fetchStudents, sendEmail, today }) {
  const students = await fetchStudents();
  const owing = students.filter((s) => s.balance > 0);
  for (const s of owing) await sendEmail(s.email, `Reminder (${today}): $${s.balance} due`);
  return owing.length;
}
 
const sent = [];
const count = await sendReminders({
  fetchStudents: async () => [{ email: "navika@example.com", balance: 0 }, { email: "advitha@example.com", balance: 45 }],
  sendEmail: async (to, text) => sent.push(`${to}: ${text}`),
  today: "2026-01-05",
});
console.log(count, sent);
Output
1 ['advitha@example.com: Reminder (2026-01-05): $45 due']

The injectable version can be tested with no network, no email server and a fixed date. In production, a small wrapper passes the real fetch-based loader, the real email sender and today's date.

Mock Functions with node:test

mock.fn(implementation?) creates a function that records every call; fn.mock.calls lists them with their arguments and results:

mock-fn.test.js▶ Try it
import { test, mock } from "node:test";
import assert from "node:assert/strict";
 
function notifyLate(students, notify) {
  for (const s of students) if (s.daysLate > 10) notify(s.name, s.daysLate);
}
 
test("notifies only students more than 10 days late", () => {
  const notify = mock.fn();
  notifyLate([{ name: "Navika", daysLate: 3 }, { name: "Srihitha", daysLate: 16 }, { name: "Advitha", daysLate: 40 }], notify);
 
  assert.equal(notify.mock.callCount(), 2);
  assert.deepEqual(notify.mock.calls.map((c) => c.arguments), [["Srihitha", 16], ["Advitha", 40]]);
});
Output
✔ notifies only students more than 10 days late (0.487833ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2.527458

Mocking Methods and fetch

mock.method(object, "name", implementation) temporarily replaces a method, and restores it after the test. That includes globals such as fetch:

mock-fetch.test.js▶ Try it
import { test, mock, afterEach } from "node:test";
import assert from "node:assert/strict";
 
async function getTotals() {
  const res = await fetch("https://api.example.com/totals");
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}
 
afterEach(() => mock.restoreAll());
 
test("returns totals from the API", async () => {
  const fake = mock.method(globalThis, "fetch", async () => Response.json({ grade9: 165 }));
  assert.deepEqual(await getTotals(), { grade9: 165 });
  assert.equal(fake.mock.calls[0].arguments[0], "https://api.example.com/totals");
});
 
test("throws on a server error", async () => {
  mock.method(globalThis, "fetch", async () => new Response("down", { status: 503 }));
  await assert.rejects(getTotals(), /HTTP 503/);
});
Output
✔ returns totals from the API (8.802709ms)
✔ throws on a server error (0.238ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 11.17275

Response.json(data) builds a realistic response object, so the code under test runs its real ok check and JSON parsing. mock.restoreAll() puts the real fetch back after each test.

Fake Timers

Code with delays, retries, debouncing or dates would make tests slow and unpredictable. mock.timers replaces setTimeout, setInterval and Date with fake versions you advance instantly:

fake-timers.test.js▶ Try it
import { test, mock } from "node:test";
import assert from "node:assert/strict";
 
function debounce(fn, ms) {
  let t;
  return (...args) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); };
}
 
test("debounce runs once, after the quiet period", () => {
  mock.timers.enable({ apis: ["setTimeout"] });
  const save = mock.fn();
  const debounced = debounce(save, 30_000);
 
  debounced("a");
  debounced("b");
  mock.timers.tick(29_999);
  assert.equal(save.mock.callCount(), 0);
  mock.timers.tick(1);
  assert.deepEqual(save.mock.calls[0].arguments, ["b"]);
  mock.timers.reset();
});
 
test("fake Date gives a fixed today", () => {
  mock.timers.enable({ apis: ["Date"], now: new Date("2026-01-05T10:00:00Z") });
  assert.equal(new Date().toISOString().slice(0, 10), "2026-01-05");
  mock.timers.reset();
});
Output
✔ debounce runs once, after the quiet period (0.922916ms)
✔ fake Date gives a fixed today (1.973833ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 4.999458

A 30-second debounce was tested in about a millisecond. For code using Temporal, inject the current date instead (pass today as a parameter), which needs no mocking at all.

Testing DOM Code

Code that manipulates the page needs a document. Options:

ApproachHowTrade-off
Keep logic out of the DOMTest pure functions; keep DOM code thinFastest; covers most logic
Simulated DOM (jsdom, happy-dom)Run tests in Node.js with a fake documentFast; no real layout or rendering
Real browser (Playwright, Vitest browser mode)Run in Chromium, Firefox, WebKitMost realistic; slower

This course's own checker is an example of the real-browser approach: each page example runs in headless Chromium, and its console output is compared with the expected text. The same idea, as a self-checking page:

dom-test.html
<button id="add">Add $50</button>
<p id="total">Total: $0</p>
<script type="module">
  let total = 0;
  const totalEl = document.querySelector("#total");
  document.querySelector("#add").addEventListener("click", () => {
    total += 50;
    totalEl.textContent = `Total: $${total}`;
  });

  const expect = (label, ok) => console.log(`${ok ? "PASS" : "FAIL"} ${label}`);
  expect("starts at $0", totalEl.textContent === "Total: $0");
  setTimeout(() => expect("two clicks show $100", totalEl.textContent === "Total: $100"), 400);
</script>
Output
PASS starts at $0
PASS two clicks show $100

In a real project, Playwright drives the page and asserts on it directly: await page.click("#add"), then await expect(page.locator("#total")).toHaveText("Total: $50").

The Test Pyramid

LevelTestsSpeedHow many
UnitOne function or class, with doubles for dependenciesMillisecondsMany (hundreds)
IntegrationSeveral parts together: your API handler with a real test databaseSecondsSome
End-to-end (E2E)The whole app in a real browser, like a userSeconds to minutesA few critical paths (log in, record a payment)

Most confidence per minute comes from unit tests of business logic, backed by a handful of E2E tests for the flows that must never break. Too many E2E tests make suites slow and flaky; too few let integration mistakes through.

A Test for Every Bug

When you fix a bug, first write a test that fails because of it, then fix the code so it passes. The test documents the bug and stops it from coming back (a regression test):

regression.test.js▶ Try it
import { test } from "node:test";
import assert from "node:assert/strict";
 
// Bug report: a student with exactly a $0.10 + $0.20 balance was shown as still owing money.
const owesMoney = (payments, fee) => Math.round(fee * 100) - payments.reduce((s, p) => s + Math.round(p * 100), 0) > 0;
 
test("regression: 0.10 + 0.20 paid against a 0.30 fee is fully paid", () => {
  assert.equal(owesMoney([0.1, 0.2], 0.3), false);
});
Output
✔ regression: 0.10 + 0.20 paid against a 0.30 fee is fully paid (0.229792ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2.156917

In Practice

The Fee Tracker's retrying API client, fully tested without a network or real waiting: fetch is mocked to fail twice then succeed, and fake timers skip the backoff delays:

retry.test.js▶ Try it
import { test, mock } from "node:test";
import assert from "node:assert/strict";
 
async function fetchWithRetry(url, { retries = 3, baseDelay = 1000, fetchFn = fetch, sleep } = {}) {
  for (let attempt = 0; ; attempt++) {
    const res = await fetchFn(url);
    if (res.ok || res.status < 500 || attempt === retries) return res;
    await sleep(baseDelay * 2 ** attempt);
  }
}
 
test("retries server errors with exponential backoff", async () => {
  const responses = [new Response("", { status: 503 }), new Response("", { status: 502 }), Response.json({ ok: true })];
  const fetchFn = mock.fn(async () => responses.shift());
  const sleep = mock.fn(async () => {});
 
  const res = await fetchWithRetry("/api/totals", { fetchFn, sleep });
 
  assert.equal(res.status, 200);
  assert.equal(fetchFn.mock.callCount(), 3);
  assert.deepEqual(sleep.mock.calls.map((c) => c.arguments[0]), [1000, 2000]);
});
 
test("does not retry client errors", async () => {
  const fetchFn = mock.fn(async () => new Response("", { status: 404 }));
  const res = await fetchWithRetry("/api/missing", { fetchFn, sleep: async () => {} });
  assert.equal(res.status, 404);
  assert.equal(fetchFn.mock.callCount(), 1);
});
Output
✔ retries server errors with exponential backoff (8.046958ms)
✔ does not retry client errors (0.086875ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 9.902958

Injecting sleep (instead of calling setTimeout directly) made the delays trivially testable: the test checks the requested waits (1 and 2 seconds) without spending them.

Common Mistakes

Calling real services in unit tests. Slow and flaky. Inject and mock the boundary.

Mocking everything, including your own logic. Tests then check the mocks, not the code.

Forgetting to restore mocks. Later tests get the fake. Use afterEach(() => mock.restoreAll()).

Tests depending on today's date. Inject the date or use fake timers.

Only end-to-end tests. Slow suites that break for unclear reasons. Build on unit tests.

Practice

Challenge: Test autoSave(getText, save, ms), which calls save(getText()) every ms milliseconds, using fake timers: after 3 intervals, save must have been called 3 times with the latest text.

Show solution
autosave.test.js▶ Try it
import { test, mock } from "node:test";
import assert from "node:assert/strict";
 
const autoSave = (getText, save, ms) => setInterval(() => save(getText()), ms);
 
test("saves the latest text on every interval", () => {
  mock.timers.enable({ apis: ["setInterval"] });
  let text = "draft 1";
  const save = mock.fn();
  const id = autoSave(() => text, save, 5000);
 
  mock.timers.tick(5000);
  text = "draft 2";
  mock.timers.tick(10_000);
 
  assert.equal(save.mock.callCount(), 3);
  assert.deepEqual(save.mock.calls.map((c) => c.arguments[0]), ["draft 1", "draft 2", "draft 2"]);
  clearInterval(id);
  mock.timers.reset();
});
Output
✔ saves the latest text on every interval (0.615334ms)
ℹ tests 1
ℹ suites 0
ℹ pass 1
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2.504708
 
✓ 7 example(s) checked with Node.js v26.13.1, 0 failed

Quick check: Testing in practice

3 questions
1What does dependency injection make easier?
2What does mock.timers let a test do?
3What should most of a test suite consist of?

Key Takeaways

NeedTool
Record callsmock.fn()
Replace a method or fetchmock.method(obj, "name", impl)
Control timemock.timers.enable(), tick(ms)
Realistic responsesResponse.json(data), new Response(body, { status })
Clean upmock.restoreAll(), mock.timers.reset()
Real browser testsPlaywright

Was this tutorial helpful?

Lesson 128 of 139