Skip to article content
FrontendXLesson 02 / 24

Test Structure, Isolation and Determinism

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 30 minutes · 6 exercises

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

What you will be able to do

#
  • Structure a test with clear setup, action and assertion phases.
  • Name tests so a failure report identifies the broken behavior.
  • Recognize shared state that makes tests order-dependent.

Overview

#

One behavior per test

A test should assert one behavior. When a test asserts five unrelated things, the first failure hides the rest, and the report does not tell you what broke. Split it. Each test then has a single reason to fail, which is exactly what you want at 2am.

Naming is documentation

A test name is a sentence a future reader will see in a failure report. works tells nothing. returns an empty array when the input is empty tells the reader what contract broke without opening the file. Name the subject, the condition and the expected result.

Isolation: no test depends on another

Tests must pass in any order and in isolation. The classic failure is shared mutable state: a module-level object that one test mutates and another test reads. If the suite passes in file order and fails when a single test runs alone, you have an isolation bug, not a code bug.

snippet.js
const store = { items: [] };

function addItem(item) {
  store.items.push(item);
  return store.items.length;
}

// Test A leaves store.items = ['a']
// Test B expects addItem('b') to return 1, but it returns 2

The fix is to create fresh state per test, usually in a beforeEach hook, or to make the code under test accept its state as a parameter instead of closing over a module singleton.

Determinism: same input, same result

A deterministic test produces the same result every run. Sources of nondeterminism include the current time, random numbers, the network, the file system, and iteration order of unordered collections. Control each one: inject a clock, seed the random generator, stub the network, and sort before comparing. A test that passes locally and fails in CI is usually nondeterministic, not wrong.

Arrange, Act, Assert

Write tests in three visual blocks. Arrange builds the inputs. Act calls the code once. Assert checks the outcome. Keeping one act per test makes it obvious what caused the observed value. If you need two acts, you usually need two tests.

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

    Two tests share the module-level `store` above. Test A runs first and adds 'a'. What does Test B print?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    // after Test A ran
    console.log(addItem('b'));
    Choose the best answer
  2. Exercise 2Explain

    Explain why a suite that passes in a fixed order can still be broken.

    Reveal the reference answer
    reference.javascript
    Passing in one order only proves the tests are compatible with that order. If a test depends on state another test created, running them in a different order, running one alone, or running them in parallel exposes the hidden dependency. A healthy suite passes in any order and in isolation, because each test builds the state it needs.

    The answer should identify order dependence as a latent defect that a single passing order cannot detect.

  3. Exercise 3Implement

    Refactor `addItem` so it does not close over shared module state. `const s1 = createStore(); const s2 = createStore(); console.log(addItem(s1, 'a'), addItem(s1, 'b'), addItem(s2, 'c'))` should print `1 2 1`.

    starter.javascript
    const store = { items: [] };
    function addItem(item) {
      store.items.push(item);
      return store.items.length;
    }

    Reveal the reference answer
    reference.javascript
    function createStore() {
      return { items: [] };
    }
    function addItem(store, item) {
      store.items.push(item);
      return store.items.length;
    }

    Authored expected output: 1 2 1

    Passing the store as a parameter removes the shared singleton. Each caller owns its own store, so tests cannot leak state into each other and the function is trivially testable.

  4. Exercise 4Debug

    This test passes locally but fails at midnight because it uses the real clock. Make it deterministic by injecting the time.

    starter.javascript
    function isWeekend() {
      const day = new Date().getDay();
      return day === 0 || day === 6;
    }
    console.log(isWeekend());

    Reveal the reference answer
    reference.javascript
    function isWeekend(date) {
      const day = date.getDay();
      return day === 0 || day === 6;
    }
    const friday = new Date(2026, 10, 13, 12, 0, 0); // local Friday
    console.log(isWeekend(friday));

    Authored expected output: false

    Reading the real clock makes the result depend on when the test runs. Accepting a date parameter lets the test supply a fixed local date, so the outcome is the same on every machine at every time. Constructing the date locally (not from a UTC string) keeps getDay independent of the test machine's timezone.

  5. Exercise 5Test

    Write two isolated tests for a `pushAndCount` helper, each creating its own state, and prove they do not interfere.

    starter.javascript
    function createStore() {
      return { items: [] };
    }
    function pushAndCount(store, item) {
      store.items.push(item);
      return store.items.length;
    }

    Reveal the reference answer
    reference.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }
    const a = createStore();
    assertEqual(pushAndCount(a, 'x'), 1, 'first push in store a');
    const b = createStore();
    assertEqual(pushAndCount(b, 'y'), 1, 'first push in store b');
    assertEqual(pushAndCount(a, 'z'), 2, 'second push in store a');
    console.log('isolation verified');

    Authored expected output: isolation verified

    Each test creates a fresh store, so the count for store b is 1 even though store a already has an item. The final assertion confirms store a kept its own history.

  6. Exercise 6Interview

    In an interview, explain how you would find the cause of a test that fails only in CI.

    Reveal the reference answer
    reference.javascript
    First I check whether the CI failure is deterministic or intermittent by rerunning. If intermittent, I look for nondeterminism: real time, random values, network, unordered iteration, or shared state between tests. I run the single test in isolation and in a random order to expose order dependence. If it is deterministic in CI only, I compare environment differences such as timezone, locale, Node version and available resources. I fix the source of nondeterminism rather than adding a retry.

    The answer should distinguish flaky from environment-specific failures and should reject retries as a fix.

Common misconceptions

#
  • Test order does not matter because the runner sorts tests.
  • A test name is cosmetic and can be auto-generated.
  • Using the real system clock makes tests more realistic and therefore better.

Follow-up practice

#
  • testing-test-doubles
  • testing-async-and-timers

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.