Testing JavaScript with Jest & Mocha
Published by Brayan K
Master automated testing to catch bugs before production. Learn unit tests, mocking, async testing, API testing, and test-driven development with Jest and Mocha.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A test needs an observation that could prove you wrong
A test runner discovers tests, executes them and reports their outcomes. An assertion compares an observed result with a chosen expectation. Jest includes a runner, expect matchers and mocking tools. Mocha supplies a runner and lifecycle tools; these examples pair it with Node’s built-in strict assertions, so a separate assertion package is unnecessary.
Put each framework panel in its own example.test.cjs inside a practice project. Install the named development dependency, then run npx jest example.test.cjs --runInBand or npx mocha example.test.cjs. CommonJS keeps this introduction’s module setup explicit. These fixtures were run with Jest 30.5.2 and Mocha 12.0.3; a project may use another supported version or an ESM configuration. The browser JavaScript editor cannot substitute for either runner.
State the exact boundary before writing the assertion [jest]
function canEnter(age) {
// The stated contract includes exactly 18.
return age >= 18;
}
test("accepts the first permitted age", () => {
const actual = canEnter(18); // Act on the boundary, not a convenient sample.
expect(actual).toBe(true); // Assert an externally visible outcome.
});
test("rejects one below the boundary", () => {
expect(canEnter(17)).toBe(false);
});Output
PASS: accepts the first permitted age
PASS: rejects one below the boundary
Tests: 2 passed, 0 failedRun this complete CommonJS test file with the named framework in Node. The output is a normalized report captured from that runner; timing, paths and terminal decoration are omitted.
A passing result establishes only what these inputs and assertions observed. It does not prove that every input is valid, that the browser works, or that a live API follows the same contract. Choose normal, boundary and invalid cases from the specification. Do not copy the implementation’s formula into the expected result and call that an independent check.
Make a broken implementation fail before trusting the suite
function canEnter(age) { return age >= 18; }
console.log(canEnter(18), canEnter(17));
// ✅ Expected output:
// true falseThe equal-boundary test exposes a real off-by-one defect [jest]
function canEnter(age) { return age > 18; }
test("accepts the first permitted age", () => {
expect(canEnter(18)).toBe(true);
});
test("rejects one below the boundary", () => {
expect(canEnter(17)).toBe(false);
});Output
FAIL: accepts the first permitted age
PASS: rejects one below the boundary
Tests: 1 passed, 1 failedRun this complete CommonJS test file with the named framework in Node. The output is a normalized report captured from that runner; timing, paths and terminal decoration are omitted.
This intentionally failing run is useful evidence: the same test distinguishes the documented boundary from the wrong implementation. The earlier corrected comparison makes both cases pass. Red–green–refactor means observing a relevant failure, implementing the intended behavior, then changing structure while preserving that behavior. A test that passes before it can reach its assertion may be misleading.
function assertEqual(actual, expected) {
if (!Object.is(actual, expected)) throw new Error("expected exact boundary to be accepted");
}
assertEqual(18 > 18, true);
// ✅ Expected error:
// Error: expected exact boundary to be acceptedThis tiny assertion function is plain JavaScript, not a replacement for Jest or Mocha. Its thrown error illustrates why a failure reaches a runner. Logging “failed” and returning normally is not the same thing as failing a test.
Compare the thing the contract promises
Object shape and object identity are different assertions [jest]
test("new records have equal data without shared identity", () => {
const actual = { id: "a", tags: ["draft"] };
const expected = { id: "a", tags: ["draft"] };
expect(actual).toEqual(expected);
expect(actual).not.toBe(expected);
});
test("strict shape can distinguish an explicit undefined field", () => {
expect({ id: "a", note: undefined }).toEqual({ id: "a" });
expect({ id: "a", note: undefined }).not.toStrictEqual({ id: "a" });
});Output
PASS: new records have equal data without shared identity
PASS: strict shape can distinguish an explicit undefined field
Tests: 2 passed, 0 failedRun this complete CommonJS test file with the named framework in Node. The output is a normalized report captured from that runner; timing, paths and terminal decoration are omitted.
Use identity assertions when sharing the same object is part of the API. Use structural assertions when selected values matter. Jest’s toEqual and toStrictEqual deliberately differ for some shapes; choose one rather than assuming “deep equality” is a single universal rule. For approximate floating-point calculations choose a stated tolerance; for exact integer counts test exact values. Numbers & Math owns numeric representation.
Use Mocha with Node’s strict assertion library [mocha]
const assert = require("node:assert/strict");
describe("selected record", function () {
it("copies public fields without retaining the original object", function () {
const source = { id: "a", secret: "omit" };
const result = { id: source.id };
assert.deepEqual(result, { id: "a" });
assert.notEqual(result, source);
});
it("rejects an invalid argument", function () {
function requireText(value) {
if (typeof value !== "string") throw new TypeError("text required");
return value;
}
assert.throws(() => requireText(3), { name: "TypeError", message: "text required" });
});
});Output
PASS: selected record copies public fields without retaining the original object
PASS: selected record rejects an invalid argument
Tests: 2 passed, 0 failedRun this complete CommonJS test file with the named framework in Node. The output is a normalized report captured from that runner; timing, paths and terminal decoration are omitted.
Pass a function to a synchronous throw assertion so the assertion controls the call. Calling the function before passing it may throw outside the assertion. A rejected promise requires an asynchronous rejection assertion instead. Neither framework’s matcher vocabulary should be assumed to work unchanged in the other.
Tell the runner when asynchronous work has finished
Return or await the promise containing the assertion [jest]
async function loadLabel(id) {
if (id !== "a") throw new Error("missing label");
return "Draft";
}
test("waits for successful loading", async () => {
await expect(loadLabel("a")).resolves.toBe("Draft");
});
test("waits for the rejection assertion", async () => {
await expect(loadLabel("unknown")).rejects.toThrow("missing label");
});Output
PASS: waits for successful loading
PASS: waits for the rejection assertion
Tests: 2 passed, 0 failedRun this complete CommonJS test file with the named framework in Node. The output is a normalized report captured from that runner; timing, paths and terminal decoration are omitted.
Mocha also waits for the returned promise [mocha]
const assert = require("node:assert/strict");
describe("asynchronous label", function () {
it("awaits the observable result", async function () {
const load = async () => "Draft";
assert.equal(await load(), "Draft");
});
it("asserts an expected rejection", async function () {
await assert.rejects(async () => { throw new Error("offline"); }, /offline/);
});
});Output
PASS: asynchronous label awaits the observable result
PASS: asynchronous label asserts an expected rejection
Tests: 2 passed, 0 failedRun this complete CommonJS test file with the named framework in Node. The output is a normalized report captured from that runner; timing, paths and terminal decoration are omitted.
An assertion inside an unreturned promise can happen after a test has already been reported complete. Use one completion mechanism: return/await a promise, or use the runner’s callback contract for a callback API. Do not both return a promise and call done. A timeout is a guard against a stuck test; increasing it is not a fix for forgotten completion or a leaked handle. Async/Await Architecture & Best Practices owns application coordination.
Avoid real sleeps and network calls in a unit test when you can inject a clock, scheduler or transport. Fake timers control the timer APIs they replace; they do not prove browser rendering, operating-system scheduling or a real server. Restore replaced globals and mocks after each test.
Isolate fixtures and use mocks to test an explicit boundary
Fresh mutable fixtures prevent order-dependent assertions [jest]
let items;
beforeEach(() => { items = ["seed"]; });
test("can add an item", () => {
items.push("added");
expect(items).toEqual(["seed", "added"]);
});
test("starts with its own fixture", () => {
expect(items).toEqual(["seed"]);
});Output
PASS: can add an item
PASS: starts with its own fixture
Tests: 2 passed, 0 failedRun this complete CommonJS test file with the named framework in Node. The output is a normalized report captured from that runner; timing, paths and terminal decoration are omitted.
Check observable behavior and the selected dependency call [jest]
function makeSave(write) {
return async text => {
if (typeof text !== "string" || text.trim() === "") throw new TypeError("title required");
return write({ title: text.trim() });
};
}
test("passes normalized data and preserves the result", async () => {
const write = jest.fn().mockResolvedValue({ id: "a" });
const save = makeSave(write);
await expect(save(" Draft ")).resolves.toEqual({ id: "a" });
expect(write).toHaveBeenCalledTimes(1);
expect(write).toHaveBeenCalledWith({ title: "Draft" });
});
test("rejects invalid intent before writing", async () => {
const write = jest.fn();
await expect(makeSave(write)(" ")).rejects.toThrow(TypeError);
expect(write).not.toHaveBeenCalled();
});Output
PASS: passes normalized data and preserves the result
PASS: rejects invalid intent before writing
Tests: 2 passed, 0 failedRun this complete CommonJS test file with the named framework in Node. The output is a normalized report captured from that runner; timing, paths and terminal decoration are omitted.
The mock verifies this function’s collaboration contract. It does not verify an HTTP request, database constraint or production permission. Keep some integration checks against real adapters where those behaviors matter. An end-to-end browser journey covers a different boundary again. Choose layers by the failure you need to detect; do not equate more mocks or a coverage percentage with stronger evidence.
Line coverage means code was visited, not that the assertions would detect a wrong result. Mutation checks deliberately introduce a plausible defect and ask whether the suite fails. A surviving mutation can reveal a missing case or an irrelevant mutation; inspect it rather than treating the percentage as an automatic quality grade. Avoid committing test.only or skipped cases accidentally.
Guided exercise: separate the action from its expected result
Fill the three literal hints. The small browser-compatible assertion is deliberately labelled as JavaScript practice; the framework panels above show how real runners execute a suite. Keep the expected values independent of the implementation.
function canEnter(age) { return age >= 18; }
function check(condition, message) {
if (!condition) throw new Error(message);
}
check(canEnter(___) === true, "exact boundary"); // 👉 replace ___ with 18
check(canEnter(17) === ___, "below boundary"); // 👉 replace ___ with false
const actual = { id: "a" };
check(Object.hasOwn(actual, ___), "selected field"); // 👉 replace ___ with "id"
console.log("three assertions passed");
// ✅ Expected output:
// three assertions passedBrief: a booking contract whose boundaries matter
Write a Jest suite for canBook(capacity, taken, requested). Capacity is a safe integer from 0 through 100; taken is a safe integer from 0 through capacity; requested is a safe integer from 1 through 6. Invalid counts throw RangeError without coercion. Valid inputs return whether the remaining places cover the request, including an exact fit. The operation only quotes capacity; it does not reserve a seat or prevent concurrent overbooking.
Include normal success, exact fit, one place short, zero capacity, full capacity, lower/upper request limits, fractional values, nonfinite values and a numeric string. Give each failure a name that identifies its case. Prove the suite catches changing the final greater-than-or-equal comparison to a strict greater-than comparison. Then restore the implementation.
The suite checks independent boundaries and invalid classes [jest]
function canBook(capacity, taken, requested) {
if (!Number.isSafeInteger(capacity) || capacity < 0 || capacity > 100 ||
!Number.isSafeInteger(taken) || taken < 0 || taken > capacity ||
!Number.isSafeInteger(requested) || requested < 1 || requested > 6)
throw new RangeError("invalid booking counts");
return capacity - taken >= requested;
}
describe("canBook contract", () => {
test.each([
[10, 4, 6, true], [10, 5, 6, false], [0, 0, 1, false],
[100, 0, 6, true], [1, 0, 1, true], [1, 1, 1, false]
])("capacity %i taken %i request %i", (capacity, taken, requested, expected) => {
expect(canBook(capacity, taken, requested)).toBe(expected);
});
test.each([
[-1, 0, 1], [101, 0, 1], [10, -1, 1], [10, 11, 1],
[10, 0, 0], [10, 0, 7], [10, 0, 1.5], ["10", 0, 1],
[NaN, 0, 1], [Infinity, 0, 1]
])("rejects invalid counts %#", (capacity, taken, requested) => {
expect(() => canBook(capacity, taken, requested)).toThrow(RangeError);
});
});Output
PASS: canBook contract capacity 10 taken 4 request 6
PASS: canBook contract capacity 10 taken 5 request 6
PASS: canBook contract capacity 0 taken 0 request 1
PASS: canBook contract capacity 100 taken 0 request 6
PASS: canBook contract capacity 1 taken 0 request 1
PASS: canBook contract capacity 1 taken 1 request 1
PASS: canBook contract rejects invalid counts 0
PASS: canBook contract rejects invalid counts 1
PASS: canBook contract rejects invalid counts 2
PASS: canBook contract rejects invalid counts 3
PASS: canBook contract rejects invalid counts 4
PASS: canBook contract rejects invalid counts 5
PASS: canBook contract rejects invalid counts 6
PASS: canBook contract rejects invalid counts 7
PASS: canBook contract rejects invalid counts 8
PASS: canBook contract rejects invalid counts 9
Tests: 16 passed, 0 failedRun this complete CommonJS test file with the named framework in Node. The output is a normalized report captured from that runner; timing, paths and terminal decoration are omitted.
This runnable JavaScript counterpart demonstrates selected cases of the same function. The parameterized suite above remains the real Jest verification.
function canBook(capacity, taken, requested) {
if (!Number.isSafeInteger(capacity) || capacity < 0 || capacity > 100 ||
!Number.isSafeInteger(taken) || taken < 0 || taken > capacity ||
!Number.isSafeInteger(requested) || requested < 1 || requested > 6)
throw new RangeError("invalid booking counts");
return capacity - taken >= requested;
}
console.log(canBook(10, 4, 6), canBook(10, 5, 6));
console.log(canBook(0, 0, 1), canBook(1, 0, 1));
for (const request of [0, 7, 1.5, "1"]) {
try { canBook(10, 0, request); }
catch (error) { console.log(error.name, error.message); }
}
// ✅ Expected output:
// true false
// false true
// RangeError invalid booking counts
// RangeError invalid booking counts
// RangeError invalid booking counts
// RangeError invalid booking countsA passing unit suite does not test a booking database transaction. That belongs to the adapter and integration boundary described in Writing Maintainable & Scalable Code Architecture. For a changed public contract, update the test from the new requirement; do not change an expectation merely to make a surprising implementation pass.
Practice quiz
What does a passing mocked repository test establish?
- The caller followed the tested dependency contract
- The production database committed
- Every network failure is handled
- The user is authorized
Answer: The caller followed the tested dependency contract. A local mock cannot establish remote adapter behavior.
What does this complete program print? const a={x:1},b={x:1};console.log(a===b,JSON.stringify(a)===JSON.stringify(b));
- true true
- false true
- true false
- false false
Answer: false true. Different object identities can still contain the same selected data.
Why await an asynchronous assertion inside a test?
- To start a new thread
- To make a network request deterministic
- So the runner observes its completion and failure
- To disable timeouts
Answer: So the runner observes its completion and failure. The test must return or await the work it asks the runner to observe.
What does this complete program print? let data;function setup(){data=[]}setup();data.push(1);setup();console.log(data.length);
- 1
- 2
- undefined
- 0
Answer: 0. Fresh setup prevents state leaking from a previous test.
Which input best distinguishes available >= requested from available > requested?
- Exactly enough places
- Far more places
- A negative string
- A missing callback
Answer: Exactly enough places. The equality boundary differentiates those two implementations.
What does this complete program print? let calls=0;function save(x){if(x.trim()==="")throw Error("blank");calls++}try{save(" ")}catch{}console.log(calls);
- 1
- 0
- 2
- undefined
Answer: 0. The invalid-input case verifies no dependency effect occurred.
What does 100% line coverage prove by itself?
- Every input is correct
- Every assertion is useful
- The measured lines were executed
- The app is secure
Answer: The measured lines were executed. Execution coverage does not show whether wrong results would be detected.
What does this complete program print? const original={a:1};const selected={a:original.a};console.log(Object.is(original,selected),selected.a);
- true 1
- true undefined
- false undefined
- false 1
Answer: false 1. Value and identity assertions answer different questions.
Continue this course
- Previous: Intro to TypeScript & Strong Typing Concepts
- Next: Building Simple SPAs with Vanilla JavaScript — Build a single-page application with client-side routing and state
- Quick reference: JavaScript cheat sheet