Skip to article content
FrontendXLesson 10 / 24

Integration Testing Across Modules

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.

intermediate · about 40 minutes · 6 exercises

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

What you will be able to do

#
  • Compose real units and double only the outer boundary.
  • Choose the smallest set of collaborators that still exercises the wiring.
  • Diagnose whether a failure is in a unit or in the wiring.

Overview

#

Integration tests check the seams

Unit tests prove each part works alone. Integration tests prove the parts work together. The defects they catch are wiring defects: a function called with arguments in the wrong order, a store updated but not re-read, an event emitted but never subscribed. These defects are invisible to unit tests because each unit is correct in isolation.

Double only the outer boundary

An integration test should use real implementations for the units under integration and a double only for the outermost dependency, usually the network or the clock. If you mock every collaborator, you are back to a unit test with extra ceremony and you will not catch wiring defects.

snippet.js
// real store + real reducer + fake network
// the test proves the fetch result flows through the reducer into the store

The middle layer is where bugs hide

A form that validates, a store that persists, a hook that subscribes: these are integrations. Test that an action on one layer produces the expected state on another. Assert on the observable end state, not on intermediate calls, so the test survives internal refactoring.

Diagnose the failure layer

When an integration test fails, ask whether a unit is broken or the wiring is broken. Run the relevant unit test. If it passes, the defect is in how the units are connected, which is exactly what the integration test is for. This diagnosis is faster than reading the whole stack.

Keep integration tests few and meaningful

Integration tests are slower and broader than unit tests. Use them for the critical seams: data flow from the API into the UI, form submission into the store, authentication into the router. Do not write an integration test for every pair of functions; that belongs to unit tests.

Determinism still applies

An integration test with a real boundary is flaky. Keep the boundary doubled and the internal layers real, so the test is fast, deterministic and still exercises the wiring.

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

    A reducer adds a task, and a store wraps the reducer. After dispatching `add` once, what does `store.getState().tasks.length` return?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    function reducer(state, action) {
      if (action.type === 'add') return { tasks: [...state.tasks, action.task] };
      return state;
    }
    function createStore(reducer, initial) {
      let state = initial;
      return {
        dispatch: (action) => { state = reducer(state, action); },
        getState: () => state,
      };
    }
    const store = createStore(reducer, { tasks: [] });
    store.dispatch({ type: 'add', task: { id: 1 } });
    console.log(store.getState().tasks.length);
    Choose the best answer
  2. Exercise 2Explain

    Explain why mocking every collaborator in an integration test defeats its purpose.

    Reveal the reference answer
    reference.javascript
    If every collaborator is a mock, the test only verifies that the code under test calls the mocks in the expected order. It never runs the real interaction between units, so a wiring defect such as a wrong argument order or a missing subscription goes undetected. The test becomes a unit test with more setup and less value. Integration tests must keep the internal collaborators real and double only the outer boundary.

    The answer should connect over-mocking to the loss of real inter-unit behavior and the specific defects that then escape.

  3. Exercise 3Implement

    Implement `createTaskService(fetchImpl)` with `load()` that fetches `/api/tasks`, and an `add(task)` that appends to an internal list. `const s = createTaskService(fetchImpl); await s.load(); s.add({id:2}); console.log(s.list().length)` should print `2` when the fake returns one task.

    starter.javascript
    function createTaskService(fetchImpl) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function createTaskService(fetchImpl) {
      let tasks = [];
      return {
        async load() {
          const response = await fetchImpl('/api/tasks');
          tasks = await response.json();
        },
        add(task) {
          tasks = [...tasks, task];
        },
        list() {
          return tasks;
        },
      };
    }

    Authored expected output: 2

    The service keeps its own list, loads it from the injected fetch, and appends on add. The test exercises the real service logic with only the network doubled.

  4. Exercise 4Debug

    The store updates but the UI never re-renders because the subscriber is never called. Find the wiring defect so `console.log('rendered')` prints after dispatch.

    starter.javascript
    function createStore(reducer, initial) {
      let state = initial;
      const listeners = [];
      return {
        subscribe: (fn) => listeners.push(fn),
        dispatch: (action) => { state = reducer(state, action); },
        getState: () => state,
      };
    }
    const store = createStore((s, a) => s, {});
    store.subscribe(() => console.log('rendered'));
    store.dispatch({ type: 'noop' });

    Reveal the reference answer
    reference.javascript
    function createStore(reducer, initial) {
      let state = initial;
      const listeners = [];
      return {
        subscribe: (fn) => listeners.push(fn),
        dispatch: (action) => {
          state = reducer(state, action);
          for (const fn of listeners) fn();
        },
        getState: () => state,
      };
    }
    const store = createStore((s, a) => s, {});
    store.subscribe(() => console.log('rendered'));
    store.dispatch({ type: 'noop' });

    Authored expected output: rendered

    dispatch updates state but never notifies subscribers, so the render callback is never invoked. Calling each listener after the state change closes the wiring gap, which is exactly the defect an integration test catches.

  5. Exercise 5Test

    Write an integration test that loads tasks from a fake API into a store and proves the store holds the loaded tasks.

    starter.javascript
    function reducer(state, action) {
      if (action.type === 'set') return { tasks: action.tasks };
      return state;
    }
    function createStore(reducer, initial) {
      let state = initial;
      const listeners = [];
      return {
        subscribe: (fn) => listeners.push(fn),
        dispatch: (action) => { state = reducer(state, action); for (const fn of listeners) fn(); },
        getState: () => state,
      };
    }

    Reveal the reference answer
    reference.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }
    async function test() {
      const fakeFetch = async () => ({ ok: true, status: 200, json: async () => [{ id: 1 }, { id: 2 }] });
      const store = createStore(reducer, { tasks: [] });
      let renders = 0;
      store.subscribe(() => { renders += 1; });
      const response = await fakeFetch('/api/tasks');
      store.dispatch({ type: 'set', tasks: await response.json() });
      assertEqual(store.getState().tasks.length, 2, 'tasks loaded');
      assertEqual(renders, 1, 'subscriber notified');
      console.log('integration verified');
    }
    test();

    Authored expected output: integration verified

    The test uses a real reducer and real store with only the network doubled. It asserts the end state and that subscribers were notified, which is the wiring this integration exists to verify.

  6. Exercise 6Interview

    In an interview, explain how you decide what to double in an integration test.

    Reveal the reference answer
    reference.javascript
    I identify the outermost dependency that is slow, nondeterministic or external, such as the network, the clock or the file system, and double only that. Everything inside the integration stays real so the test exercises the actual wiring. If a collaborator is fast and deterministic, I do not double it, because doubling it removes the behavior I am trying to verify.

    The answer should define the boundary by cost and nondeterminism and keep internal collaborators real.

Common misconceptions

#
  • Integration tests should mock every collaborator for speed.
  • Integration tests replace unit tests.
  • A failing integration test always means the integration is wrong.

Follow-up practice

#
  • testing-e2e-browser
  • testing-capstone-quality-task-board

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.