Jest interview questions and answers

Jest interview questions check whether you can write unit tests that fail for the right reason: choosing the right matcher, replacing a dependency with a mock or spy, controlling time with fake timers, and awaiting async code so a broken promise cannot pass silently. Freshers are asked about matchers and the test lifecycle; experienced developers get questions on module mocking, flaky suites, coverage and how Jest fits with React Testing Library.

By Published 9 min read

How Jest comes up in interviews

Jest questions appear in frontend, Node.js and full-stack loops, and in SDET or QA interviews where the team expects testers to read and write unit tests. There are three common formats. A quick knowledge round asks you to explain matchers, mocks and the test lifecycle. A practical round hands you a small function, often one that calls an API or uses setTimeout, and asks you to test it live. A review round shows you an existing test that passes when it should not and asks you to find out why. The last format is where many candidates struggle, because the bug is usually a missing await or a mock that leaks between tests.

Fundamentals: matchers, structure and lifecycle

Jest questions for freshers and first screens
QuestionWhat it testsWhat a strong answer shows
What does Jest give you out of the box?ScopeA test runner, an assertion library (expect), mocking, fake timers, snapshot testing and coverage reporting, with little setup for a plain JavaScript project.
toBe versus toEqual?EqualitytoBe uses Object.is, so two separate objects with the same fields are not equal. toEqual compares recursively by value, which is what you want for objects and arrays.
When would you use toStrictEqual?EqualityWhen { a: undefined } and {} must count as different, or when a class instance should not equal a plain object with the same fields.
How do you compare floating point results?MatcherstoBeCloseTo(0.3) instead of toBe(0.3), because 0.1 + 0.2 is not exactly 0.3 in binary floating point.
How do you assert that a function throws?MatchersWrap the call: expect(() => parse("")).toThrow("empty input"). Passing parse("") directly runs it before expect can catch the error.
What is the order of beforeAll, beforeEach, afterEach and afterAll?LifecyclebeforeAll once per describe block, beforeEach before every test (outer blocks first), afterEach after every test (inner blocks first), afterAll once at the end.
test or it?StructureThey are aliases. Teams pick one so names read well, such as it("rejects an expired card").
How do you run the same test with many inputs?Parametrized teststest.each with a table of cases, so each input shows up as its own named test in the report.
What do test.only and test.skip do, and what is the risk?HygieneThey focus on or skip tests while you work. Committed by mistake, they silently shrink the suite, so many teams block them with a lint rule.
How does Jest find test files?ConfigurationBy default it looks for files in __tests__ folders and files ending in .test.js or .spec.js (and the TypeScript variants), controlled by testMatch or testRegex.
Jest questions for freshers and first screens. Scroll sideways on a small screen.

Mocks, spies and module mocking

  • What is the difference between `jest.fn()` and `jest.spyOn()`? jest.fn() creates a brand new fake function. jest.spyOn(obj, "method") wraps an existing method so you can watch calls, and by default the real method still runs unless you add a mock implementation.
  • `mockReturnValue`, `mockImplementation` or `mockResolvedValue`? Return a fixed value, run custom logic based on arguments, or return a resolved promise for async code. The Once variants queue values for consecutive calls, which is how you simulate "fail, then succeed".
  • What do `clearAllMocks`, `resetAllMocks` and `restoreAllMocks` each do? Clear wipes recorded calls. Reset also removes mocked return values and implementations. Restore puts the original methods back for spies made with spyOn. The config options clearMocks and restoreMocks apply them between every test.
  • Why can you call `jest.mock()` below the imports and still have it work? Babel-based transforms hoist jest.mock calls to the top of the file, so the mock is registered before the module is required. That is also why a factory cannot use outer variables unless their names start with mock.
  • How do you mock only one export of a module? Use a factory that spreads jest.requireActual("./module") and overrides the one function you need to fake.
  • What is a manual mock? A file in a __mocks__ folder next to the module. For node packages it sits beside node_modules and applies automatically; for your own modules you still call jest.mock() to use it.
  • How do you check how a mock was called? toHaveBeenCalledTimes, toHaveBeenCalledWith and toHaveBeenLastCalledWith, or read mockFn.mock.calls directly when you need the arguments of a specific call.
  • Does `jest.mock` work with native ES modules? ESM support in Jest has been marked experimental, and mocking there uses jest.unstable_mockModule with dynamic imports. Most projects still let a transform compile tests to CommonJS, which is why the classic jest.mock keeps working.
const mailer = require("./mailer");

async function signUp(email) {
  if (!email.includes("@")) throw new Error("invalid email");
  const user = { email, createdAt: Date.now() };
  await mailer.sendWelcome(email);
  return user;
}

module.exports = { signUp };
signup.js: a module with a dependency worth mocking.
const { signUp } = require("./signup");
const mailer = require("./mailer");

jest.mock("./mailer", () => ({ sendWelcome: jest.fn().mockResolvedValue(true) }));

afterEach(() => jest.clearAllMocks());

test("sends one welcome email to the new user", async () => {
  const user = await signUp("ana@example.com");
  expect(user.email).toBe("ana@example.com");
  expect(mailer.sendWelcome).toHaveBeenCalledTimes(1);
  expect(mailer.sendWelcome).toHaveBeenCalledWith("ana@example.com");
});

test("rejects a bad address without sending anything", async () => {
  await expect(signUp("not-an-email")).rejects.toThrow("invalid email");
  expect(mailer.sendWelcome).not.toHaveBeenCalled();
});
signup.test.js: the mailer module is replaced, so no email is sent and the call can be checked.

Async tests and fake timers

Intermediate questions where small mistakes hide real bugs
QuestionWhat it testsWhat a strong answer shows
Why does an async test pass even when the code is broken?Async disciplineThe test did not return or await the promise, so Jest finished the test before the rejection or the assertion ran. Await it, or return it.
How do you test a promise that should reject?Async matchersawait expect(promise).rejects.toThrow(...). Forgetting the await here is the same bug as above.
What does expect.assertions(n) protect against?Safety netIt fails the test unless exactly n assertions ran, which catches a catch block that never executed.
When would you still use the done callback?CallbacksFor callback-style APIs that do not return a promise. Call done in every path, and pass errors to done(err), or the test times out instead of failing clearly.
What do fake timers replace?Time controlsetTimeout, setInterval, and in the default modern implementation also Date, so you can move time forward with jest.advanceTimersByTime(ms) instead of waiting.
runAllTimers versus runOnlyPendingTimers?TimersrunAllTimers keeps running until no timers remain, so a timer that reschedules itself never empties the queue and Jest aborts with an infinite-loop error. runOnlyPendingTimers runs only what is queued right now.
Why does advancing fake timers sometimes not resolve a promise?Timers and microtasksA promise callback runs as a microtask after the timer fires. The async timer helpers, such as advanceTimersByTimeAsync, flush those between steps; with the sync helpers you need extra awaits.
How do you freeze "now" for a test?Datesjest.useFakeTimers() then jest.setSystemTime(new Date("2026-01-01")), and restore real timers after the test.
Intermediate questions where small mistakes hide real bugs. Scroll sideways on a small screen.
async function fetchWithRetry(fetchFn, url, { retries = 2, delayMs = 1000 } = {}) {
  for (let attempt = 0; ; attempt++) {
    try {
      return await fetchFn(url);
    } catch (err) {
      if (attempt >= retries) throw err;
      await new Promise((resolve) => setTimeout(resolve, delayMs * 2 ** attempt));
    }
  }
}

module.exports = { fetchWithRetry };
retry.js: retries a failing call with exponential backoff.
const { fetchWithRetry } = require("./retry");

beforeEach(() => jest.useFakeTimers());
afterEach(() => jest.useRealTimers());

test("retries after a failure and returns the first success", async () => {
  const fetchFn = jest.fn()
    .mockRejectedValueOnce(new Error("timeout"))
    .mockResolvedValueOnce({ status: 200 });

  const promise = fetchWithRetry(fetchFn, "/orders");
  await jest.advanceTimersByTimeAsync(1000);

  await expect(promise).resolves.toEqual({ status: 200 });
  expect(fetchFn).toHaveBeenCalledTimes(2);
  expect(fetchFn).toHaveBeenLastCalledWith("/orders");
});

test("gives up after the last retry", async () => {
  const fetchFn = jest.fn().mockRejectedValue(new Error("down"));
  const promise = fetchWithRetry(fetchFn, "/orders", { retries: 2, delayMs: 100 });
  const settled = expect(promise).rejects.toThrow("down");

  await jest.advanceTimersByTimeAsync(100 + 200);

  await settled;
  expect(fetchFn).toHaveBeenCalledTimes(3);
});
retry.test.js: fake timers skip the real waits, so both tests finish in milliseconds.

Snapshots, coverage and configuration

  • What is a snapshot test good for, and what goes wrong? It records serialized output and fails when it changes, which suits stable output like an error message format. Large component snapshots get updated with -u without anyone reading the diff, so they stop testing anything.
  • Inline snapshot or file snapshot? toMatchInlineSnapshot writes the expected value into the test file, which keeps it small and reviewable. Prefer it for short output.
  • What do the four coverage numbers mean? Statements, branches, functions and lines executed during the run. Branch coverage is the most telling, because it shows the else paths nobody exercised.
  • Is 100% coverage a good target? It shows code ran, not that anything was asserted. A coverageThreshold that stops coverage from dropping is more useful than a fixed high number.
  • `testEnvironment: "node"` or `"jsdom"`? Node for server code, jsdom when the code touches document or window. In recent versions jsdom is a separate package (jest-environment-jsdom) that you install yourself.
  • What are `setupFiles` and `setupFilesAfterEnv` for? The first runs before the test framework loads (polyfills, environment variables). The second runs after, so it can add custom matchers such as those from @testing-library/jest-dom.
  • How do you handle CSS imports and path aliases? moduleNameMapper maps \.css$ to a stub and ^@/(.*)$ to your source folder, so Jest resolves them like the bundler does.
  • How do you run Jest with TypeScript? Through babel-jest with the TypeScript preset (fast, no type checking) or ts-jest (type checks during tests, slower). Many teams type check separately with tsc.

Jest with React Testing Library

  • Why pair Jest with React Testing Library instead of testing component internals? RTL renders the component into jsdom and lets you query it the way a user sees it, so tests survive refactors that do not change behavior.
  • `getBy`, `queryBy` or `findBy`? getBy throws if the element is missing, queryBy returns null so you can assert absence, and findBy returns a promise that waits for the element to appear after async work.
  • Which query should you reach for first? getByRole with an accessible name, then label text, then visible text. getByTestId is the fallback when nothing accessible fits.
  • `fireEvent` or `userEvent`? fireEvent dispatches a single DOM event. userEvent simulates the full sequence a person causes (focus, key down, input, key up), so it catches more real bugs. Its methods are async in current versions.
  • What does the `act` warning mean? A state update happened outside what the test was waiting for. Usually the fix is to await a findBy query or waitFor for the result, not to wrap code in act by hand.
  • How do you test a component that fetches data? Mock the network at the request level (for example with Mock Service Worker) or mock the data module, then await the rendered result with findBy.

Experienced and scenario questions

Questions for senior developers and SDETs
QuestionWhat it testsWhat a strong answer shows
A test passes alone but fails when the whole suite runs. Where do you look?IsolationState shared across tests: a module-level variable, a mock not cleared, fake timers left on, or a global patched and not restored. jest.resetModules() and the restoreMocks option help; so does running the file with --runInBand to see ordering effects.
The suite takes ten minutes in CI. What do you try?SpeedFind slow files with --verbose timing, replace real network and disk with mocks, check for real timers and long waits, use --shard across CI machines, and run only changed tests locally with --onlyChanged.
How do you know you are mocking too much?Test designWhen every collaborator is faked, the test only proves the mocks were called in an order. Mock at boundaries you do not own (network, clock, randomness) and keep your own logic real.
How do you deal with a flaky Jest test?ReliabilityReproduce with a repeated run, look for real time, random data, shared state or unawaited promises, fix the cause, and avoid blanket jest.retryTimes as a permanent answer.
Unit test with Jest or end-to-end test in a browser?Test strategyLogic and edge cases belong in fast unit tests; a few end-to-end tests check that the pieces work together. The Cypress questions cover the browser side.
Would you move a project from Jest to Vitest?JudgmentVitest reuses most of the Jest API and fits Vite projects well. Weigh the migration cost, plugin support and how much custom Jest config exists before switching.
How do you organize tests in a monorepo?ScaleThe projects option runs several configurations (node and jsdom, different packages) in one Jest run with one coverage report.
Questions for senior developers and SDETs. Scroll sideways on a small screen.

Fictional example

Answering "This test is green, but the feature is broken. Why?"
Interviewer
Here is the test: test("saves the order", () => { expect(save(order)).resolves.toBe(true); });. Production saves are failing, yet this passes. What is wrong?
Candidate
The expectation on resolves returns a promise, and the test neither awaits nor returns it. Jest sees a synchronous function that finished without throwing and reports it as passed. The rejection arrives after the test is over, so it either gets lost or surfaces later as an unhandled rejection that is not tied to this test, which is confusing to debug. I would make the test async and write await expect(save(order)).resolves.toBe(true). Then I would check the other tests in that file for the same pattern, because it is usually copied. To stop it coming back, I would turn on the ESLint rules from the Jest plugin that flag unawaited expect promises, and for tests that assert inside a catch I would add expect.assertions(1) so a skipped branch fails instead of passing.

A one-week Jest practice plan

  1. Day 1: matchers and lifecycleWrite a test file for a small utility module using toEqual, toThrow, toBeCloseTo and test.each. Add beforeEach and log the order hooks run in.
  2. Day 2: mocksMock a module with jest.mock, spy on a method with jest.spyOn, and check what changes when you swap clearAllMocks for restoreAllMocks.
  3. Day 3: async and timeRun the retry example above. Then delete the await before the resolves assertion and change the expected status to 500: instead of a clean test failure, the mismatch escapes the test and shows up as a stray error, or not at all.
  4. Day 4: React componentsTest a form with React Testing Library: fill it with userEvent, submit it, and wait for the success message with findByRole.
  5. Day 5: broken testsTake three tests and break them on purpose: leak a mock, leave fake timers on, share a module variable. Practice explaining each failure out loud.
  6. Day 6 and 7: mock interviewHave someone hand you an untested function with a network call and a timer, and test it in thirty minutes while talking through your choices.

Unit testing is one layer of a wider quality picture. The automation testing questions cover where unit tests sit in the test pyramid, and frontend developer interview questions cover the rest of a UI loop.

A practical Jest round is mostly talking while typing, and it is hard to judge your own explanation in the moment. Natively, an AI interview assistant for Mac and Windows, transcribes a mock session so you can check afterwards whether you explained why a test needed await or just added it. During practice it can read a screenshot of a failing test or an error message and suggest what to check, help with the code you are writing, and, with Pro or the free trial, tailor suggestions to the résumé and job description you add. The transcript and notes stay available to review once the session ends.

Questions people ask

What Jest questions are asked in interviews?

Expect toBe versus toEqual, jest.fn versus jest.spyOn, how jest.mock is hoisted, testing async code and rejections, fake timers, snapshot testing, coverage and how Jest works with React Testing Library.

What is the difference between jest.fn and jest.spyOn?

jest.fn creates a new fake function. jest.spyOn wraps an existing method on an object so you can record its calls, and the original runs unless you give the spy a mock implementation.

Why does my async Jest test pass when it should fail?

The test did not await or return the promise, so Jest ended the test before the assertion or rejection happened. Make the test async and await the expectation.

What Jest questions do experienced developers get?

Tests that pass alone but fail in the suite, slow suites in CI, over-mocking, flaky tests, coverage thresholds, ES module mocking and organizing tests across a monorepo.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP