Skip to article content
FrontendXLesson 03 / 24

Test Doubles: Stubs, Spies, Mocks and Fakes

Build a working model of automated testing from assertions to unit, component, API, integration, contract and end-to-end tests, then apply it to a single progressive task-board capstone where each milestone adds a real defect, a failing test, a corrected implementation and an expected result.

beginner · about 35 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Distinguish stubs, spies, mocks and fakes by purpose.
  • Replace a slow or nondeterministic dependency with a double.
  • Avoid over-mocking that tests the double instead of the code.

Overview

#

Why doubles exist

A unit test should fail for one reason: the unit's behavior changed. Real dependencies get in the way. A network call is slow and unreliable. A clock moves. A database needs setup. A test double is a stand-in that removes that dependency so the test stays fast and deterministic.

Four kinds, four purposes

A stub returns canned answers. A spy records how it was called. A mock is a stub with built-in expectations about calls. A fake is a working but simplified implementation, such as an in-memory repository. The names are often used loosely, but the purposes differ: stubs control input, spies observe output, mocks assert interactions, fakes replace a subsystem.

snippet.js
function createSpy() {
  const calls = [];
  const spy = (...args) => {
    calls.push(args);
    return undefined;
  };
  spy.calls = calls;
  return spy;
}

const onSave = createSpy();
const editor = { save: onSave };
editor.save('draft');
console.log(onSave.calls.length); // 1

Prefer fakes and stubs over interaction mocks

A test that asserts save was called with exactly ('draft', { force: false }) breaks whenever the call signature changes, even if behavior is correct. Interaction assertions are brittle. Prefer asserting on the observable result: what the store contains, what the user sees, what value was returned. Use a spy when the interaction itself is the behavior under test, such as 'the analytics event is sent once'.

Do not mock what you are testing

If you mock the function under test, the test proves nothing about it. Mock only the collaborators at the boundary. If a unit needs five mocks to run, that is a design signal: the unit has too many dependencies and should be split.

Fakes keep tests honest

An in-memory fake of a repository exercises the real calling code against real logic, just not a real database. It catches integration mistakes that a stub would hide, because a stub only returns what you programmed it to return.

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.

  1. Exercise 1Predict

    What does this script print?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    const spy = (...args) => { spy.calls = (spy.calls || []); spy.calls.push(args); };
    spy('a');
    spy('b');
    console.log(spy.calls.length, spy.calls[1][0]);
    Choose the best answer
  2. Exercise 2Explain

    Explain the difference between a stub and a mock, and when each is appropriate.

    Reveal the reference answer
    reference.javascript
    A stub provides canned return values so the code under test can proceed; it does not care how or whether it was called. A mock adds expectations about calls and fails when they are not met. Use a stub when you only need the dependency to return a value. Use a mock when the interaction itself is the contract, such as 'exactly one analytics event is emitted'. Prefer stubs and fakes because interaction expectations are brittle.

    The answer should center on control of input versus assertion of interaction, and should note the brittleness of interaction assertions.

  3. Exercise 3Implement

    Implement `createStub(returnValue)` that returns a function which always returns `returnValue` and records its call count on `.callCount`. `const s = createStub(7); console.log(s(), s(), s.callCount)` should print `7 7 2`.

    starter.javascript
    function createStub(returnValue) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function createStub(returnValue) {
      const stub = () => {
        stub.callCount += 1;
        return returnValue;
      };
      stub.callCount = 0;
      return stub;
    }

    Authored expected output: 7 7 2

    The stub closes over returnValue and increments its own callCount property on each invocation. It ignores arguments, which is what makes it a pure input control.

  4. Exercise 4Debug

    This test mocks the very function it is supposed to test, so it can never fail. Fix it to test the real `formatPrice`.

    starter.javascript
    const formatPrice = (n) => '$' + n.toFixed(2);
    const mocked = () => '$0.00';
    console.log(mocked(5) === '$0.00' ? 'pass' : 'fail');

    Reveal the reference answer
    reference.javascript
    const formatPrice = (n) => '$' + n.toFixed(2);
    const result = formatPrice(5);
    if (result === '$5.00') {
      console.log('pass');
    } else {
      throw new Error('expected $5.00 but got ' + result);
    }

    Authored expected output: pass

    Asserting on a hand-written stub of the function under test proves only that the stub returns what it was written to return. Calling the real function and comparing to the expected string tests actual behavior.

  5. Exercise 5Test

    Write a test that proves `track` calls the injected `send` exactly once with the event name.

    starter.javascript
    function track(send, name) {
      send({ event: name });
    }

    Reveal the reference answer
    reference.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }
    const calls = [];
    const send = (payload) => calls.push(payload);
    track(send, 'signup');
    assertEqual(calls.length, 1, 'one send');
    assertEqual(calls[0].event, 'signup', 'event name');
    console.log('track verified');

    Authored expected output: track verified

    The spy records the payloads. The assertions check both the number of calls and the argument, which is exactly the interaction contract `track` must satisfy.

  6. Exercise 6Interview

    In an interview, explain when a fake is better than a mock.

    Reveal the reference answer
    reference.javascript
    A fake is better when the dependency has real behavior the code under test depends on, such as a repository that stores and retrieves items. A fake implements that behavior simply, so the test exercises real calling logic. A mock only replays programmed responses and asserts calls, so it can pass while the integration is broken. I use fakes for stateful collaborators and mocks only when the interaction itself is the requirement.

    The answer should connect fakes to exercising real logic and mocks to interaction contracts, and should mention the risk of mocks hiding integration defects.

Common misconceptions

#
  • Mocks and stubs are the same thing.
  • More mocks make a test more rigorous.
  • It is fine to mock the function you are trying to test.

Follow-up practice

#
  • testing-unit-pure-functions
  • testing-network-and-api

Related resources

#

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.

© 2026 FrontendX. All rights reserved.