Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 30 ยท Practice and Review

Jest Interview Questions

Prepare for Jest interviews: toBe vs toEqual, mocks vs spies, clear vs reset vs restore, fake timers, snapshots, async pitfalls and test strategy, with runnable stand-ins.

Interviewers rarely ask you to recite the API. They ask why: why toEqual and not toBe, why a test passed that should have failed, how you would test code that uses the clock. This lesson collects the questions that come up most often, with short answers you can say out loud and the reasoning behind them.

Jest cannot run on this site, so Jest code is read-only. Two runnable stand-ins at the end let you see the underlying JavaScript behavior with Node's assert and node:test mocks. They are stand-ins, not Jest. Every topic links to the lesson that teaches it in depth.

What interviewers probe

Precision Do you pick the right matcher?
Isolation Do you know what to fake and why?
Pitfalls Can you spot a test that cannot fail?
Strategy What deserves a test at all?

A calm "it depends, because..." beats a memorized definition.

1 / 2

Matchers

What is the difference between toBe, toEqual and toStrictEqual? toBe uses Object.is, so it checks identity for objects and treats NaN as equal to itself. toEqual compares recursively by value and ignores properties whose value is undefined. toStrictEqual is stricter: it also checks that undefined properties match, that array holes match, and that objects have the same class. Use toBe for primitives, toEqual for plain data, and toStrictEqual when types matter. See Common Matchers.

How do you compare floating-point numbers? With toBeCloseTo(expected, digits), because 0.1 + 0.2 is not exactly 0.3. See Numbers and Strings.

How do you assert that a function throws? Wrap the call: expect(() => parse("x")).toThrow("message"). If you call the function directly, it throws before expect runs and the test fails with the original error instead. See Errors and Custom Matchers.

When would you write a custom matcher? When the same multi-line check repeats and you want a readable assertion and a precise failure message. expect.extend({ toBeValidSlug(received) { ... } }) returns { pass, message }.

Mocks and spies

What is the difference between jest.fn(), jest.spyOn() and jest.mock()? jest.fn() creates a new mock function you pass in yourself. jest.spyOn(obj, "method") wraps an existing method, calls through by default, and can be restored. jest.mock("./module") replaces a whole module for the importing code. See Mock Functions with jest.fn, Spying with jest.spyOn and Mocking Modules.

What do mockClear, mockReset and mockRestore do? mockClear erases recorded calls and results. mockReset does that and also removes any mocked return value or implementation. mockRestore does everything mockReset does and, for a spy, puts the original method back. Projects often set restoreMocks: true so nothing leaks between tests.

Why is jest.mock hoisted? Imports run before the rest of a file, so a mock registered after them would arrive too late. The Babel transform used by Jest moves jest.mock calls above the imports. A consequence is that the factory cannot freely use variables from the outer scope, unless their names start with mock.

When is mocking a bad idea? When the mock re-implements the real logic, so the test only proves the mock works. Prefer a small real collaborator or an injected fake, and mock only slow, random or external things: network, time, disk, other services.

Timers

How do fake timers work, and why use them? jest.useFakeTimers() replaces setTimeout, setInterval and related functions, and optionally Date, with a controllable clock. advanceTimersByTime(ms) moves it forward, runAllTimers() flushes everything. Tests become instant and deterministic instead of sleeping. If the code mixes promises and timers, use the async variant advanceTimersByTimeAsync so pending promise callbacks run between ticks. See Mocking Timers, Dates and HTTP.

Snapshots

When are snapshots a good idea? For large output that is tedious to write by hand and changes rarely: a serialized error report, a generated config, a rendered component tree. They are a bad idea for small values (a plain assertion is clearer) and when the output contains timestamps or random ids.

What are the risks? People accept diffs without reading them (-u), and a snapshot records current behavior, correct or not. Review snapshot changes like code, keep them small, and in CI run with --ci so a missing snapshot fails instead of being silently written. See Snapshot Testing.

Async code

A test passes but the code is clearly wrong. What do you check first? Whether the promise was awaited or returned. Without await, the test function ends before the assertion settles. expect.assertions(n) is a safety net that fails if fewer assertions ran. See Testing Promises and Async/Await.

When do you use the done callback? Rarely: only for old callback APIs you cannot wrap. Better to turn them into promises. Mixing done with an async function is an error in Jest, and forgetting to call done makes the test time out. See Callbacks and the done Callback.

Strategy and tooling

How do you keep tests independent? Create fresh data in beforeEach, restore mocks and timers, avoid module-level mutable state, and never depend on test order. Jest runs each test file in its own module registry, but tests inside one file share their state. See Test Isolation and Shared State.

How is coverage useful and misleading? It tells you what never ran, not what is well tested. A line can run without any assertion about it. Treat thresholds as a floor, and look at branch coverage and at the uncovered lines, not only the percentage. See Coverage and Test Quality.

What would you test first in a new code base? Pure business logic with many branches (pricing, validation), then the boundaries (API handlers, database access) with a few integration tests, and only a handful of end-to-end checks. Test behavior users depend on, not private helper functions.

How do you debug a flaky test? Run it alone, then with --runInBand, then in a loop. Typical causes are shared state, real timers, real network, dependence on date or locale, and un-awaited promises. Remove the source of nondeterminism rather than adding retries.

Stand-in 1: equality is a family of questions

Jest's matchers build on JavaScript comparison primitives. This stand-in shows the three questions behind toBe, toEqual and toStrictEqual using Node's assert. It is NOT Jest's equality algorithm, which has more rules.

Node.js Stand-in: identity, loose and strict equality

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.

Stand-in 2: clear, reset and restore

Node's own mocks have the same three ideas. resetCalls() is like mockClear, mockImplementation changes behavior, and restore() brings the original method back. Again, these are Node mocks standing in for Jest's.

Node.js Stand-in: clearing calls versus restoring a method

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.

The last line shows that forEach hands the callback three arguments (value, index, array), a classic surprise that call records make visible. The key line is the restored call: after restore() the method is the original again, which is the guarantee that keeps one test's spy from changing the next test.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which matcher treats { a: 1, b: undefined } and { a: 1 } as different?

    toEqual ignores properties set to undefined; toStrictEqual does not. toBe would fail for any two separate objects.
  2. 2. A spy was created with jest.spyOn(obj, 'method'). Which call reinstalls the original method?

    Only mockRestore removes the wrapper and puts the original function back on the object.
  3. 3. Why can a test with expect(promise).resolves.toBe(1) and no await pass even when the promise rejects?

    Without await or return, nothing makes the test wait, so the failing assertion happens after the test is already over.
  4. 4. What does high line coverage guarantee?

    Coverage measures execution, not correctness. A line can run without any assertion about its effect.

Summary

  • Be ready to explain why behind each tool, not just what it does.
  • toBe is identity, toEqual is value equality ignoring undefined properties, toStrictEqual also checks types.
  • jest.fn makes a new mock, spyOn wraps an existing method, jest.mock replaces a module; cleanup goes clear, reset, restore.
  • Fake timers make time-based code instant; use the async helpers when promises are involved.
  • Snapshots are for big, stable output; unawaited promises are the classic way a test cannot fail.
  • Keep tests independent, mock only what is slow or nondeterministic, and treat coverage as a floor.

Finally, keep the essentials on one page with the Jest Cheat Sheet.