Testing JavaScript
Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.
What you will be able to do
#- Write deterministic unit tests with arrange, act and assert.
- Use fake timers and test doubles to isolate behavior.
- Choose between unit, integration and end-to-end tests.
Overview
#What a test is for
A test is a small program that states an expectation and fails loudly when it breaks. A good test is fast, deterministic and focused on one behavior. Arrange the inputs, act by calling the code, then assert the outcome. If a test needs a paragraph to explain, the unit under test is probably too large.
function assertEqual(actual, expected, label) {
if (!Object.is(actual, expected)) {
throw new Error(label + ': expected ' + expected + ' but got ' + actual);
}
}
assertEqual(add(1, 2), 3, 'adds two numbers');
Determinism and doubles
Time, randomness and the network make tests flaky. Fake timers advance the clock deliberately, and a stub or spy replaces a dependency so the test controls it. A test double should stand in for a boundary, not for the logic you are testing, or the test proves nothing.
Levels of testing
A unit test covers one function or module in isolation. An integration test checks that several units work together, such as a request handler and its database. An end-to-end test drives the real application through the user interface. The pyramid is a guide: many fast unit tests, fewer integration tests, and a small number of end-to-end tests for critical paths. Coverage is a signal, not a goal.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
What does this assertion do?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.javascriptassertEqual(0.1 + 0.2, 0.3, 'float sum');Exercise 2Explain
Explain the difference between a unit test and an integration test.
starter.texttest('handler returns 200', () => handler(request));Reveal the reference answer
reference.textA unit test exercises one small piece in isolation, with its dependencies replaced by doubles, so a failure points at that piece. An integration test runs several real pieces together, such as a handler and a database, to check that their contract holds. Unit tests are fast and precise; integration tests catch wiring and contract bugs that unit tests cannot see.Authored expected output: isolation versus cooperation
The answer should contrast isolated scope with real cooperation and name what each level catches.
Exercise 3Implement
Implement `expectEqual(actual, expected)` that throws an Error with a readable message when the values differ.
starter.javascriptfunction expectEqual(actual, expected) { // your code here }Reveal the reference answer
reference.javascriptfunction expectEqual(actual, expected) { if (!Object.is(actual, expected)) { throw new Error('expected ' + JSON.stringify(expected) + ' but got ' + JSON.stringify(actual)); } }Authored expected output: no output when equal, an Error when different
Object.is gives a precise comparison, and JSON.stringify makes the message readable for objects and arrays. Throwing lets the test runner catch and report the failure.
Exercise 4Debug
This test is flaky because it depends on real time. Rewrite it to be deterministic.
starter.javascripttest('debounce fires once', (done) => { const fn = debounce(spy, 100); fn(); fn(); setTimeout(() => { expect(spy).toHaveBeenCalledTimes(1); done(); }, 150); });Reveal the reference answer
reference.javascripttest('debounce fires once', () => { vi.useFakeTimers(); const spy = vi.fn(); const fn = debounce(spy, 100); fn(); fn(); vi.advanceTimersByTime(100); expect(spy).toHaveBeenCalledTimes(1); vi.useRealTimers(); });Authored expected output: the test passes without waiting on the real clock
Fake timers let the test advance time deterministically, so the assertion runs at the exact moment the debounce should fire. There is no race with the real clock.
Exercise 5Test
Write assertions that prove a function under test is called with the expected arguments using a spy.
starter.javascriptfunction assertEqual(actual, expected, label) { if (JSON.stringify(actual) !== JSON.stringify(expected)) throw new Error(label + ': unexpected value'); }Reveal the reference answer
reference.javascriptfunction spy() { const calls = []; const fn = (...args) => { calls.push(args); return args[0] * 2; }; fn.calls = calls; return fn; } const double = spy(); const result = double(21); assertEqual(double.calls, [[21]], 'records the arguments'); assertEqual(result, 42, 'returns the real result'); console.log('all assertions passed');Authored expected output: all assertions passed
The spy records each call's arguments and still returns the real value, so the test can assert both the interaction and the result.
Exercise 6Interview
How do you decide what to test first in an untested codebase?
Reveal the reference answer
reference.textI start with the code that changes most often and the paths where a bug is most expensive, such as money, auth and data loss. I write characterization tests around existing behavior before refactoring, then add tests for new logic as I write it. I favor a few high-value integration tests over blanket coverage, and I treat a flaky test as a bug to fix or delete, not to ignore.The answer should prioritize risk and change frequency, mention characterization tests, and reject coverage as a goal.
Common misconceptions
#- High coverage means the code is correct.
- A test that uses the real clock is more trustworthy than one with fake timers.
- End-to-end tests should cover every branch.
Follow-up practice
#- javascript-foundations-errors-and-debugging
- javascript-foundations-async-patterns
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.