Interview questions with answers
Jest interview questions and answers
Matchers, mocks, spies, timers, snapshots and coverage. Open any question to read its model answer; the multiple-choice set marks the right option and explains it.
- Subjective
- 30
- Objective
- 30
Subjective questions 30
1jest.fn, jest.spyOn and jest.mock: what are the differences?Asked almost every time
jest.fn() creates a standalone mock function that records calls and can return set values. jest.spyOn(obj, 'method') wraps an existing method to observe it, optionally replacing the implementation, and can be restored. jest.mock('module') replaces a whole module with automatic or factory-made mocks, hoisted above imports.
2How do you test asynchronous code?Asked almost every time
Return the promise or use async/await in the test, and assert after awaiting. For rejections use await expect(promise).rejects.toThrow(). Never forget to await, or the test passes before the assertion runs. Callback-style code can use the done argument.
3What makes a good unit test?Asked almost every time
It tests one behaviour through the public interface, is independent of other tests and of order, is deterministic (no real time, network or randomness), reads clearly as arrange–act–assert, and fails with a useful message. Mock only boundaries such as network, time and external services.
4How do you mock an ES module default export?Asked almost every time
Use jest.mock('./api', () => ({ __esModule: true, default: jest.fn() })), then import the default and control it with mockResolvedValue or mockImplementation. For native ESM mode, use jest.unstable_mockModule before a dynamic import.
5How do you test error handling?Asked almost every time
For sync code, expect(() => fn()).toThrow('message') (wrapping the call in a function). For async code, await expect(fn()).rejects.toThrow(). Mock dependencies to fail with mockRejectedValue to test the code paths that handle failures.
6What should you mock and what should you not?Asked almost every time
Mock things that are slow, nondeterministic or outside your control: network, time, randomness, third-party services. Avoid mocking the code under test or simple pure helpers; too many mocks make tests pass while the real integration is broken.
7How do fake timers work?Very often asked
jest.useFakeTimers() replaces timers and Date with controllable versions. Advance time with jest.advanceTimersByTime(ms), runAllTimers or runOnlyPendingTimers, and set the clock with jest.setSystemTime. Restore with jest.useRealTimers(). Async code with timers may need the async variants.
8When should you use snapshot testing?Very often asked
For stable, serialisable output where any change should be reviewed: small rendered components, generated configs, error messages. Avoid huge snapshots that people update blindly; inline snapshots and focused assertions are often better.
9toBe vs. toEqual vs. toStrictEqual?Very often asked
toBe uses Object.is, for primitives or the same reference. toEqual compares values recursively, ignoring undefined properties. toStrictEqual also checks undefined properties, array sparseness and class types.
10How do you reset mocks between tests?Very often asked
mockClear resets calls and results, mockReset also removes implementations, mockRestore restores spied originals. Config options clearMocks, resetMocks and restoreMocks do this automatically before each test, which avoids leaking state between tests.
11Explain setup and teardown hooks.Very often asked
beforeAll/afterAll run once per file or describe block, for expensive setup such as starting a test database. beforeEach/afterEach run around every test, for fresh state. Hooks in a describe apply only to its tests.
12How do you configure Jest for TypeScript?Very often asked
Use ts-jest (type-checks during tests) or a transformer like babel-jest or @swc/jest (faster, no type checking), set testEnvironment, moduleNameMapper for path aliases and assets, and run tsc --noEmit separately for types.
13What is moduleNameMapper used for?Very often asked
It maps import paths to other modules, for path aliases like ^@/(.*)$ to <rootDir>/src/$1, and for replacing CSS or image imports with stubs (for example identity-obj-proxy for CSS modules).
14How do you test a function that uses Date.now or random values?Very often asked
Use fake timers with jest.setSystemTime(new Date(...)) to fix the current time, and spy on Math.random with jest.spyOn(Math, 'random').mockReturnValue(0.5), restoring afterwards.
15What are custom matchers?Very often asked
Functions added with expect.extend({ toBeWithinRange(received, floor, ceiling) {...} }) that return pass and a message. They make domain assertions readable; jest-dom is a popular set of custom matchers.
16How do you make a slow test suite faster?Very often asked
Run in parallel (default workers), avoid real network and timers, share expensive setup with beforeAll, use faster transformers like SWC, run only changed tests with --onlyChanged locally, and shard in CI with --shard.
17What are setupFiles vs. setupFilesAfterEach?Very often asked
setupFiles run before the test framework is installed, for polyfills and environment variables. setupFilesAfterEach run after it, so they can use expect and hooks, for example importing jest-dom matchers or global mocks.
18How do you check how many times and in what order mocks were called?Very often asked
Use toHaveBeenCalledTimes(n), toHaveBeenNthCalledWith(n, ...args) and toHaveBeenLastCalledWith. Inspect mock.calls and mock.invocationCallOrder for order across several mocks.
19How do you measure and use code coverage?Often asked
Run jest --coverage to report statement, branch, function and line coverage, and set coverageThreshold to fail builds that drop below targets. Coverage shows untested code but not test quality; aim tests at behaviour and risky branches.
20How do you mock a module partially?Often asked
Use jest.mock with a factory that spreads jest.requireActual('module') and overrides only some exports, so the rest keep their real behaviour.
21How does Jest isolate test files?Often asked
Each test file runs in its own module registry and environment (node or jsdom), often in separate worker processes in parallel. Module-level state does not leak between files, but it does between tests in the same file.
22How do you test code that uses fetch?Often asked
Mock the network boundary: jest.spyOn(global, 'fetch') with resolved responses, or better, Mock Service Worker (MSW) to intercept requests at the network level, so code under test runs unchanged.
23What are manual mocks in __mocks__ folders?Often asked
Files in a __mocks__ folder next to a module (or at the root for node_modules packages) replace that module when jest.mock('module') is called, keeping reusable mock implementations in one place.
24How do you test code with environment variables?Often asked
Save process.env, set values in beforeEach, reset modules with jest.resetModules() if the code reads them at import time, and restore the original object in afterEach.
25How do inline snapshots differ from file snapshots?Often asked
toMatchInlineSnapshot() writes the snapshot into the test file itself, so reviewers see the expected output next to the test. File snapshots live in __snapshots__. Inline ones suit small outputs.
26What does --watch do?Often asked
It reruns tests related to changed files (using Git) as you work, with an interactive menu to filter by file name or test name, which gives fast feedback during development.
27How do you test code that uses setTimeout with promises?Often asked
Use fake timers and the async helpers await jest.advanceTimersByTimeAsync(ms) or runAllTimersAsync(), which also flush promise callbacks between timers, avoiding tests that hang or finish too early.
28What is test.each?Sometimes asked
A way to run the same test with a table of inputs and expected outputs, so you can cover many cases without repeating code; titles can include values with %s or $name.
29What do .only and .skip do?Sometimes asked
test.only runs only that test in the file (useful while debugging); test.skip skips it. Neither should be committed; lint rules can block them.
30Jest vs. Vitest: how do they compare?Sometimes asked
Both have similar APIs. Vitest uses Vite's transform pipeline, supports ESM and TypeScript natively and is usually faster in Vite projects. Jest is mature with a huge ecosystem. Migration is mostly renaming jest to vi.
Objective questions 30
1Which matcher compares object contents recursively?Asked almost every time
Why: toBe checks identity.
2Which creates a mock function?Asked almost every time
Why: jest.fn records calls and returns.
3How do you assert a promise rejects?Asked almost every time
Why: .rejects unwraps the rejection.
4How do you assert a sync function throws?Asked almost every time
Why: Wrap the call in a function.
5Which makes a mock return a rejected promise?Asked almost every time
Why: For testing failure paths.
6What should usually be mocked?Asked almost every time
Why: Slow or nondeterministic parts.
7Which replaces timers with controllable fakes?Very often asked
Why: Then advance time manually.
8Which checks a mock was called with arguments?Very often asked
Why: It checks any call's arguments.
9jest.mock calls are…Very often asked
Why: babel-jest hoists them above imports.
10Which hook runs before every test?Very often asked
Why: beforeEach gives fresh state per test.
11Which option maps @/ imports in tests?Very often asked
Why: Also stubs CSS imports.
12Which sets the fake current date?Very often asked
Why: Works with fake timers.
13Which adds a custom matcher?Very often asked
Why: Returns pass and message.
14Which config runs after the framework is installed?Very often asked
Why: Can use expect.
15Which checks the second call's arguments?Very often asked
Why: Index starts at 1.
16Which restores a method wrapped by spyOn?Often asked
Why: mockRestore puts back the original.
17Which flag reports code coverage?Often asked
Why: It prints coverage tables and reports.
18Which matcher checks an array includes an item?Often asked
Why: toContain uses ===; toContainEqual compares values.
19Which environment do React component tests usually need?Often asked
Why: jsdom provides a DOM.
20Where do reusable manual mocks live?Often asked
Why: Used with jest.mock.
21Which writes the snapshot into the test file?Often asked
Why: Reviewers see it inline.
22Which advances fake timers and flushes promises?Often asked
Why: The async variant.
23Which clears the module registry?Often asked
Why: Re-import picks up new env.
24Which flag runs only tests related to changed files?Often asked
Why: It uses Git to find changed files.
25Which transformer is fast but skips type checking?Often asked
Why: Run tsc separately.
26Which runs the same test over a table of cases?Sometimes asked
Why: test.each parameterises tests.
27What does toBeCloseTo help with?Sometimes asked
Why: It tolerates rounding errors.
28Which option fails the build below a coverage level?Sometimes asked
Why: Set global or per-file thresholds.
29Which flag splits tests across CI machines?Sometimes asked
Why: e.g. --shard=1/3.
30Which ESM API mocks a module before a dynamic import?Sometimes asked
Why: For native ESM mode.
Track what you have practised and search every bank in your dashboard.
Start learning