Jest
03 / 03

Interview Questions

Jest Interview Questions

Q: What is the difference between unit, integration, and e2e tests?

  • Unit — test a single function/class in isolation; all dependencies are mocked. Fast, numerous, pinpoint failures.

  • Integration — test multiple modules together (e.g., service + real database). Slower, fewer, catch connection issues.

  • E2E — test the full system from user perspective (browser automation). Slowest, fewest, highest confidence.

Q: What is the difference between toBe and toEqual?

toBe uses Object.is (strict reference equality) — passes for primitives and identical object references. toEqual performs deep equality check — two different objects with the same structure will pass. Use toBe for primitives and same-reference checks, toEqual for objects and arrays.

Q: What is the difference between mockClear, mockReset, and mockRestore?

  • mockClear — resets mock.calls, mock.instances, mock.results. Keeps mock implementation and return values.

  • mockReset — everything mockClear does + removes mock implementation and return values.

  • mockRestore — everything mockReset does + restores the original (non-mocked) implementation. Only works on jest.spyOn() mocks.

Q: How do you test that a function throws?

// Sync
expect(() => fn(badInput)).toThrow('error message');
expect(() => fn(badInput)).toThrow(TypeError);

// Async
await expect(asyncFn(badInput)).rejects.toThrow('error message');
await expect(asyncFn(badInput)).rejects.toBeInstanceOf(NotFoundError);

Q: What is code coverage and what should you aim for?

Coverage measures what percentage of your code is executed during tests: statements, branches, functions, lines. 100% is usually impractical and not always meaningful — focus on critical business logic. A practical target is 70-80% line coverage with high coverage on core paths. Use coverage to find untested areas, not as a quality metric in itself.

Q: When should you use snapshot tests?

Snapshot tests are useful for stable UI components where you want to detect unintended visual regressions. They are a poor substitute for behavioral tests — a snapshot tells you what changed but not if the change is correct. Avoid large component snapshots (too brittle), update snapshots via --updateSnapshot after intentional changes.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free