Testing JavaScript: Unit Tests, Mocks and Coverage with node:test, Vitest and Jest
Write automated tests that catch logic bugs: how test frameworks work, assertions, Node's built-in node:test runner, Vitest and Jest, testing async code, test doubles (mocks, stubs, spies) and dependency injection, code coverage, the testing pyramid, and running tests in CI.
kvi5hnuCode Sprout team member7 min readOn this page
A linter reports suspicious code, and a type checker reports mismatched types, but neither knows what your code is supposed to do. Automated tests do: small programs that run your code with known inputs and check the outputs. They catch logic bugs, document behavior, and let you change code confidently, because a broken behavior shows up as a failing test instead of a bug report.
How a test framework works
At its core, a test framework is simple: it collects named test functions, runs each one, treats a thrown exception as a failure, and reports the results with an exit code that CI systems check. This tiny version shows the whole idea:
const assert = require("node:assert/strict");
// The essence of a test framework: register named tests, run them, report results
const tests = [];
const test = (name, fn) => tests.push({ name, fn });
async function run() {
let failed = 0;
for (const { name, fn } of tests) {
try {
await fn(); // async tests are awaited
console.log(`✔ ${name}`);
} catch (err) {
failed++;
console.log(`✖ ${name}\n expected ${JSON.stringify(err.expected)}, got ${JSON.stringify(err.actual)}`);
}
}
console.log(`${tests.length - failed} passed, ${failed} failed`);
return failed; // a real runner sets a nonzero exit code when anything failed
}
// Code under test
function slugify(title) {
return title.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-");
}
test("lowercases and joins words with dashes", () => {
assert.equal(slugify("Hello World"), "hello-world");
});
test("drops punctuation", () => {
assert.equal(slugify("Node.js: Streams!"), "node-js-streams");
});
test("handles surrounding spaces", () => {
assert.equal(slugify(" Tips "), "tips");
});
test("compares structures with deepEqual", () => {
assert.deepEqual(["a", "b"].map(slugify), ["a", "b"]);
});
test("expects an error", () => {
assert.throws(() => slugify(null), TypeError);
});
run().then((failed) => console.log("exit code would be", failed ? 1 : 0));
✔ lowercases and joins words with dashes
✖ drops punctuation
expected "node-js-streams", got "node-js-streams-"
✔ handles surrounding spaces
✔ compares structures with deepEqual
✔ expects an error
4 passed, 1 failed
exit code would be 1
The failing test found a real bug: slugify leaves a trailing dash when the title ends in punctuation. That's typical: tests are most valuable for edge cases you didn't think about while writing the code.
Assertions are the checks. Node's node:assert/strict module provides equal (compared with Object.is), deepEqual (compares structure, for objects and arrays), throws and rejects (expects an error), match (regular expression) and ok. Frameworks offer similar expect(value).toBe(...) styles. A test should check behavior through the public interface, not implementation details, so that refactoring doesn't break it.
The test runners
Three runners dominate:
node:test, built into Node (stable since Node 20). No installation; good for libraries and Node services.- Vitest: fast, Jest-compatible API, native ES modules and TypeScript, shares configuration with the Vite build tool (article 136). The usual choice for new front-end and full-stack projects.
- Jest: the long-time standard, all-in-one (runner, assertions, mocks, coverage, snapshots). Still very common, especially in existing React projects.
Our example is a function that gets a temperature in Celsius from a web API and converts it to Fahrenheit, with a bug in the conversion. Here it is with the API client passed as a parameter, so tests can supply a fake one:
// temperature.js
export async function getTemperature(city, fetchJSON) {
const url = `https://weather.example.com/api/city/${encodeURIComponent(city.toLowerCase())}`;
const { celsius } = await fetchJSON(url);
return (celsius * 5) / 9 + 32;
}
A test file for node:test:
// temperature.test.js
import { test, describe, mock } from "node:test";
import assert from "node:assert/strict";
import { getTemperature } from "./temperature.js";
describe("getTemperature", () => {
test("requests the right URL", async () => {
const fetchJSON = mock.fn(async () => ({ celsius: 0 }));
await getTemperature("New York", fetchJSON);
assert.equal(fetchJSON.mock.callCount(), 1);
assert.equal(fetchJSON.mock.calls[0].arguments[0], "https://weather.example.com/api/city/new%20york");
});
test("converts Celsius to Fahrenheit", async () => {
assert.equal(await getTemperature("x", async () => ({ celsius: 0 })), 32);
assert.equal(await getTemperature("x", async () => ({ celsius: 100 })), 212);
});
});
node --test finds files named like *.test.js and runs them. The output (shortened) shows the bug:
▶ getTemperature
✔ requests the right URL (0.4ms)
✖ converts Celsius to Fahrenheit (0.5ms)
ℹ tests 2
ℹ pass 1
ℹ fail 1
✖ converts Celsius to Fahrenheit
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ 87.55555555555556
- 212
The formula should multiply by 9 and divide by 5. After the fix, both tests pass and node --test exits with code 0. 0 °C happened to give the right answer with both formulas, which is why the second check, 100 °C, matters: choose test values that distinguish right from wrong.
The same tests in Vitest (Jest is nearly identical, with jest.fn()), using test.each to run one test with several inputs:
import { describe, test, expect, vi } from "vitest";
import { getTemperature } from "./temperature.js";
describe("getTemperature", () => {
test("requests the right URL", async () => {
const fetchJSON = vi.fn().mockResolvedValue({ celsius: 0 });
await getTemperature("New York", fetchJSON);
expect(fetchJSON).toHaveBeenCalledWith("https://weather.example.com/api/city/new%20york");
});
test.each([[0, 32], [100, 212], [-40, -40]])("%i °C is %i °F", async (c, f) => {
expect(await getTemperature("x", async () => ({ celsius: c }))).toBe(f);
});
});
Testing asynchronous code
Make the test function async and await the code under test; the runner waits for the returned promise and fails the test if it rejects. Use assert.rejects or await expect(promise).rejects.toThrow() for expected failures. The classic mistake is forgetting await: the test finishes before the assertion runs, and passes even though the code is broken.
Test doubles: mocks, stubs and spies
Unit tests should be fast and deterministic, so they replace slow or unpredictable dependencies (network, database, clock, randomness, email) with test doubles:
- A stub returns canned answers: a clock that always says 14.
- A spy records how it was called, so the test can check calls and arguments.
- A mock is the general term, and frameworks'
mock.fn(),vi.fn()andjest.fn()do both jobs.
const { mock } = require("node:test");
const assert = require("node:assert/strict");
// Code under test: depends on a clock and a mailer, both passed in
function createReminder({ now, send }) {
return {
remind(user) {
const hour = now().getHours();
if (hour < 8 || hour >= 20) return false; // don't disturb at night
send(user.email, `Hi ${user.name}, your report is ready`);
return true;
},
};
}
// Test doubles: a stubbed clock and a spy mailer
const send = mock.fn();
const daytime = createReminder({ now: () => new Date(2026, 0, 5, 14, 0), send });
const night = createReminder({ now: () => new Date(2026, 0, 5, 23, 30), send });
assert.equal(daytime.remind({ name: "Ada", email: "ada@example.com" }), true);
assert.equal(night.remind({ name: "Lin", email: "lin@example.com" }), false);
console.log("send called", send.mock.callCount(), "time(s)");
console.log("arguments:", send.mock.calls[0].arguments);
// Replacing a method on an existing object, then restoring it
const random = mock.method(Math, "random", () => 0.5);
console.log(Math.random(), Math.random(), random.mock.callCount());
random.mock.restore();
console.log("restored:", Math.random() !== 0.5 || "unlucky");
send called 1 time(s)
arguments: [ 'ada@example.com', 'Hi Ada, your report is ready' ]
0.5 0.5 2
restored: true
The reminder takes its clock and mailer as parameters (dependency injection), which makes it trivial to test both the daytime and nighttime paths. Without that, a test would have to replace a module, which frameworks support (jest.mock("./mailer"), vi.mock, or the experimental mock.module in node:test), but which couples tests to file structure. Frameworks also provide fake timers (mock.timers, vi.useFakeTimers()) to test timeouts without waiting. Mock only what you must: a test that mocks everything checks only that your mocks agree with each other.
Code coverage
Coverage tools record which lines, branches and functions your tests executed. node --test --experimental-test-coverage, vitest --coverage and jest --coverage print a table:
file | line % | branch % | funcs % | uncovered lines
temperature.js | 100.00 | 100.00 | 100.00 |
Uncovered lines show untested code, which is useful. But 100% coverage doesn't mean the code is correct: the buggy version of getTemperature had 100% coverage with only the 0 °C test. Coverage measures what ran, not what was checked.
What to test: the pyramid

- Unit tests check one function or module in milliseconds. Write many of them.
- Integration tests check modules together with real infrastructure, such as starting the HTTP server from article 130 on port 0 and calling it with
fetch, or using a test database. - End-to-end tests drive the real application in a browser with Playwright or Cypress. They catch what users would see, but they're slower and break more easily, so keep them few.
For browser code, front-end tests often run in a simulated DOM (jsdom or happy-dom, configured in Vitest or Jest), with Testing Library to interact with components the way users do. Snapshot tests (toMatchSnapshot) store output and fail when it changes, which is convenient but easy to approve without reading.
Writing the test first, watching it fail, then writing the code (test-driven development) is a useful discipline, and it's also the best way to fix a bug: first write a test that reproduces it, so it can never silently come back. Run all tests in CI on every change (article 133).
Common questions
Should I use node, Vitest or Jest?
For a Node library or service, node:test has no dependencies. For projects built with Vite, or any new front-end project, Vitest. In an existing Jest project, keep Jest; Vitest's API is close enough to migrate later if you want.
My async test passes even though the code is broken. Why?
The test probably doesn't await the promise, or doesn't return it, so the runner finishes before the assertion runs. Make the test async and await everything.
Is 100% coverage worth aiming for?
Rarely. High coverage of important logic is valuable, but the last few percent usually costs a lot and adds little. Focus on meaningful assertions and edge cases.
Summary
- A test runs code with known inputs and asserts on outputs; frameworks collect tests, report results and set the exit code.
node:testis built in; Vitest and Jest add richer tooling. Usedescribe/test, assertions such asequal,deepEqual,throwsandrejects, andawaitin async tests.- Replace slow or unpredictable dependencies with stubs and spies (
mock.fn,vi.fn,jest.fn); dependency injection makes this easy. - Coverage shows untested code but doesn't prove correctness. Write many unit tests, fewer integration tests and a few end-to-end tests, and run them in CI.
Practice Questions
Why did the buggy temperature formula pass a test that only checked 0 °C?
Answer
At 0 °C, both 0 * 5 / 9 + 32 and 0 * 9 / 5 + 32 equal 32. A test needs inputs where right and wrong code give different results, such as 100 °C (212 °F) or -40 (equal in both scales, which is a good extra check).
What's wrong with this test?
test("rejects unknown users", () => {
assert.rejects(loadUser("nobody"));
});
Answer
assert.rejects returns a promise, and the test neither awaits nor returns it, so the test finishes before the check completes and can pass even if loadUser resolves. Write it as:
test("rejects unknown users", async () => {
await assert.rejects(loadUser("nobody"));
});
How would you test a function that sends a welcome email, without sending real emails?
Answer
Pass the mail-sending function in as a dependency, or mock the mailer module, and in the test use a spy such as mock.fn(). Then assert that the spy was called once with the expected address and message.
Previous: JavaScript Tooling: Linting with ESLint and Formatting with Prettier
Next: Package Management: npm, package.json, Semantic Versioning and Lockfiles

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.