Jest · Unit tests that survive refactors

Why is test isolation important and how do you achieve it?

MediumisolationstatedeterminismUpdated Oct 2026
Quiz this track

Short answer

Each test should create and clean up its own state so it passes alone and in any order. Reset mocks, timers, globals and shared data between tests to prevent hidden coupling.

An isolated test has no dependency on what ran before it. That property lets Jest reorder or parallelise files, lets you run a single test while debugging, and makes failures reproducible. Shared mutable state breaks all three.

Common leaks

  • A spy installed in one test still active in the next
  • A module-level cache populated by an earlier case
  • Fake timers left enabled after a test
  • Rows written to a shared database without cleanup
  • A global object such as window.fetch replaced and never restored
ts
afterEach(() => {
  jest.restoreAllMocks();
  jest.useRealTimers();
  delete (globalThis as { fetch?: unknown }).fetch;
});

test("fetches the profile", async () => {
  globalThis.fetch = jest.fn().mockResolvedValue({
    ok: true,
    json: async () => ({ id: "u1" }),
  });

  await expect(loadProfile("u1")).resolves.toEqual({ id: "u1" });
});
The cleanup restores every global the test touches, so the next case starts clean.

Prefer creating state inside the test or in a beforeEach scoped to the block that needs it. Use beforeAll only for immutable or truly expensive resources. If two tests must share data, that is often a sign they should be one test or that the fixture needs a factory.

Jest isolates test files, not individual tests. Two tests in the same file share the module registry and any module-level variables unless you explicitly reset them.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Does Jest isolate each test or each test file?
  2. 2How do module-level caches break isolation?
  3. 3When is shared setup acceptable?
  4. 4How do you reproduce a failure that only happens in a full run?

Say it in the interview

Isolation means a test passes when run alone and is not affected by order. I create state per test and clean up mocks, timers, globals and database rows in afterEach. Jest isolates files, but tests in the same file still share module-level state. When a test only fails in a full run, I look for leaked state first.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Jest mock interview and get scored feedback on depth, clarity and confidence.