Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 30 ยท Hooks and Isolation

Test Isolation and Shared State

Why Jest tests pass alone but fail together: leaked state, module registries, order-dependent tests, test data factories and the usual causes of flaky tests.

You run one test and it passes. You run the whole file and it fails. You run it again and it passes. Anyone who has worked on a real test suite has seen this, and the cause is nearly always the same: tests that are not isolated. One test leaves something behind, and another test quietly depends on it.

An isolated test gives the same result whether it runs first, last, alone, or in parallel with others. This lesson shows where hidden shared state comes from in a Jest project, how to reset it, how test data factories help, and the other usual causes of flaky tests. It follows from Setup and Teardown Hooks.

Real versus stand-in. The Jest code in plain blocks is real but read-only, because the site cannot run Jest. The runnable examples are small Node programs that reproduce the same problems (a shared object, a changed environment variable, a reused default) without Jest. The jest.resetModules behavior is described, not run.

Where state hides

Module variables Counters, caches, singletons.
Globals process.env, Date, console, window.
Mocks Calls and implementations left over.
External stores A database or file shared by tests.
1 / 2

What Jest isolates for you, and what it does not

Jest does give you some isolation automatically:

  • Every test file runs in its own module registry (its own copy of every imported module) and in its own sandbox. A module-level variable that one file changes is not changed in another file. Files can also run in parallel in separate worker processes.
  • Inside a single file, however, the module registry is shared by all tests. A module is evaluated once, so a variable at the top of your source file keeps its value from one test to the next. Tests in a file also run one after another in the order they are declared.

That second point is where trouble starts.

JavaScript
// counter.js
let count = 0;
export function increment() { count += 1; return count; }
export function current() { return count; }
JavaScript
import { increment, current } from './counter.js';

test('increments to 1', () => {
  expect(increment()).toBe(1);
});

test('increments to 2', () => {
  expect(increment()).toBe(2);   // only true because the first test ran first
});

Both pass in file order. Run only the second with -t "increments to 2" and it fails with 1. The second test is order-dependent, and it will fail unpredictably the day someone reorders, skips or parallelizes tests.

Fixing leaked module state

Choose the fix that matches the cause.

  1. Design for testability. Return a fresh object from a function instead of keeping module-level state: createCounter() gives each test its own counter. This is often the best long-term fix.
  2. Reset explicitly. Export a reset() for tests (or reset the fields in beforeEach).
  3. Reload the module. jest.resetModules() clears the module registry, so the next require or dynamic import() evaluates the file again and gets fresh state. jest.isolateModules(() => { ... }) does the same inside a callback with its own sandboxed registry.
JavaScript
beforeEach(() => {
  jest.resetModules();
});

test('starts at 1 every time', () => {
  const { increment } = require('./counter.js');   // fresh copy each test
  expect(increment()).toBe(1);
});

Note that this reload trick works with require and dynamic import() used after the reset; modules you imported at the top of the file are already bound to the old copy. ESM mode adds more caveats, which we revisit in Mocking Modules.

Other places state leaks

  • process.env and other globals. A test that sets process.env.MODE = 'test' and never restores it changes every test that follows. Save the old value and restore it in afterEach, or use a helper that does so.
  • Mocks and spies. A mock keeps its recorded calls and implementation across tests. Jest has configuration options that clear, reset or restore mocks automatically (clearMocks, resetMocks, restoreMocks), covered in Spying with jest.spyOn.
  • Timers and dates. A fake clock left installed affects later tests.
  • Databases, files and servers. A test that inserts rows and does not remove them changes what the next test sees. Use a transaction that is rolled back, truncate in beforeEach, or give each test its own temporary resource.
  • Default arguments and shared fixtures. A constant object used as a default is the same object every time.

Test data factories

Hard-coded fixture objects shared between tests are a classic leak: one test mutates sampleUser and every later test sees the change. A factory is a function that builds a new object on every call, with sensible defaults and overrides for the details that matter:

JavaScript
let sequence = 0;

export function buildUser(overrides = {}) {
  sequence += 1;
  return {
    id: sequence,
    name: `User ${sequence}`,
    email: `user${sequence}@example.test`,
    role: 'member',
    tags: [],
    ...overrides,
  };
}

Now a test says only what it cares about:

JavaScript
const admin = buildUser({ role: 'admin' });
expect(canDelete(admin)).toBe(true);

The factory has two jobs: new objects each time (so mutation cannot spread), and defaults so the test is not cluttered by irrelevant fields. The one subtle trap is a shared default such as a constant { tags: [] }: spreading it copies the reference, not the array. Build nested defaults inside the function, as above.

Why tests become flaky

A flaky test passes and fails without any change to the code. Besides shared state, the common causes are:

Cause Typical symptom Fix
Real time and dates Fails near midnight or at month end Fake the clock (Mocking Timers, Dates and HTTP)
Randomness Fails one run in fifty Inject a seeded random function
Unawaited promises Passes locally, fails in CI await everything (Testing Promises and Async/Await)
Real network or services Fails when the service is slow Mock or use a local fake
Timing guesses setTimeout(..., 100) to "wait enough" Wait for the event or fake timers
Order dependence Fails when run alone or reordered Make each test self-contained
Parallel access to one resource Fails only in parallel A resource per test or per worker

Newer Jest versions can run the tests inside each file in random order with the --randomize flag, which is a cheap way to expose hidden order dependence. If a test fails only under a certain order, that is a bug in the test (or in the code), not in the shuffle.

Finally, do not "fix" flakiness by retrying until green. Retries hide real problems, and a suite people do not trust stops being useful.

Seeing order dependence

The first example below has a module-style shared registry and three tests. It runs them in written order, then in reverse order, then in reverse order again with a reset in front of every test. Watch which results change.

Node.js The same tests, three ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In declared order the second test passes only because the first one left Ada behind, and "starts empty" fails even there, because it assumed a clean registry. With a reset before each test, the dependent tests break in a useful way: "counts after a second add" now fails with 1, showing that it secretly relied on the first test. Fixing it means making that test add both users itself. Isolation does not make tests pass; it makes their real assumptions visible.

Environment and shared defaults

The second example shows two more leaks and their fixes: an environment variable that is not restored, and a shared default object versus a factory.

Node.js Restoring globals and avoiding shared defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

badBuild copies the top-level fields but the tags array is the same object in every user, so pushing to one user's tags changes all of them. goodBuild creates a new array each call, so the objects are independent, and the sequence number gives every user a unique id and email without any hand-written values.

A checklist before you commit a test

  • Does it pass when run alone with -t?
  • Does it pass when the tests in the file are shuffled?
  • Does it restore anything it changed (environment, mocks, timers, files)?
  • Does it create its own data instead of depending on a fixture another test mutates?
  • Does it avoid real time, randomness and the real network?

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A test passes with the whole file but fails when run alone with -t. What is the most likely cause?

    An order-dependent test relies on a side effect from another test. Making the test set up its own state fixes it.
  2. 2. How does Jest isolate module state?

    Each file has its own registry, so files do not affect each other. Within one file, a module is evaluated once, so top-level variables persist across tests unless you reset them.
  3. 3. What does jest.resetModules() do?

    It empties the registry. Modules you load after the reset get new state, while modules already imported at the top of the file keep the old copy.
  4. 4. Why is a constant default object like const DEFAULTS = { tags: [] } risky in a test data builder?

    Spread is shallow. Nested arrays and objects stay shared, so build nested defaults inside the factory function.
  5. 5. Which is a good response to a test that fails one run in twenty?

    Retries hide real problems. The reliable fix is to remove the nondeterminism by controlling time and randomness, isolating state and awaiting async work.

Summary

  • Jest isolates test files from each other, but tests inside one file share module state.
  • Order-dependent tests pass or fail depending on what ran before them; run tests alone and shuffled to find them.
  • Fix leaks by designing without hidden state, resetting in hooks, or reloading modules with jest.resetModules() or jest.isolateModules().
  • Restore globals such as process.env, mocks and timers after each test.
  • Use factory functions that build new objects with overridable defaults.
  • Flaky tests have causes (time, randomness, network, unawaited promises, shared resources); remove the cause rather than retrying.

Next: Mock Functions with jest.fn.