skip to content

Jest

The batteries-included JavaScript test runner: matchers, mocking, snapshots, coverage, and a config that mostly works out of the box. Interviewers ask because it is the default in most React and Node codebases.

on this pageshow

explore

questions

page 1 of 2

In a Jest 30 test, why must you return or await the promise under test, and what happens when you forget?

level: juniorimportance: must knowfreq 80%

answer

  1. when Jest decides a test is finished
  2. what the test function hands back
  3. async functions return a promise
  4. assertion runs after the verdict

basics

~20 s

Jest 30 waits only for a promise the test function hands back: returned, or awaited inside an async test. Forget that and Jest stops waiting when the function returns, so the assertion's outcome no longer decides the test.

solid answer

~40 s

Jest treats a test as finished when the test function returns, unless what it returns is a promise (and an `async` function always returns one): then Jest waits for it to settle and fails the test if it rejects. So either `return fetchJson(...).then(...)`, or make the test `async` and `await` the call or the `expect(...).resolves` / `.rejects` chain. If you only call `fetchJson(...).then(body => expect(body)...)` without returning it, the function returns `undefined`, Jest stops waiting, and the assertion runs on its own schedule: its failure may be reported late, may surface as an error outside any test, or may be lost when the file has already finished. Awaiting is not free of risk either: a promise that never settles fails the test at the 5-second default timeout.

code

javascript · 33 lines
javascript
// fetchJson.js
async function fetchJson(get, url) {
  const res = await get(url);
  if (res.status >= 500) throw new Error(`Server error ${res.status}`);
  return res.body;
}

module.exports = {fetchJson};

// fetchJson.test.js
const {fetchJson} = require('./fetchJson');

const get = async () => ({status: 200, body: {id: 7}});

// Broken (do not copy): returns undefined, so Jest never waits for then()
// test('loads the user', () => {
//   fetchJson(get, '/users/7').then(body => expect(body).toEqual({id: 7}));
// });

test('loads the user (returned promise)', () => {
  return fetchJson(get, '/users/7').then(body => {
    expect(body).toEqual({id: 7});
  });
});

test('loads the user (async/await)', async () => {
  const body = await fetchJson(get, '/users/7');
  expect(body).toEqual({id: 7});
});

test('loads the user (awaited .resolves)', async () => {
  await expect(fetchJson(get, '/users/7')).resolves.toEqual({id: 7});
});

go deeper

for a junior

Recall the rule: a Jest test of async code must return its promise or await it, and marking the function async without awaiting changes nothing.

for a middle

Explain how Jest reads the test function's return value, why an unreturned then callback runs after Jest has stopped waiting, and what the 5-second default timeout catches.

for a senior

Show how a missing await lets a broken feature ship behind a green suite, and the review habits that catch it: awaiting every modifier, assertion counts, breaking the code on purpose.

for a principal

Weigh which async style a team standardises on and how it is enforced in review, since a silent pass costs more than any failing test.

## How Jest decides that a test is finished A Jest test is a function passed to `test` (or its alias `it`). Jest calls that function and looks at **what it hands back**: - **It returns `undefined`** and threw nothing: the test is synchronous, and it has passed. - **It throws**: the test has failed with that error. - **It returns a promise**: Jest waits for the promise to settle. Fulfilled means passed; rejected means failed with the rejection reason. - **It declares a parameter**: Jest switches to the callback style and waits for that parameter, conventionally named `done`, to be called. That style has its own rules and failure modes. - **It returns anything else**: Jest 30 fails the test with `test functions can only return Promise or undefined.` Nothing in that list mentions promises the test merely *creates*. Jest has no way to know that a `fetchJson(...)` call started inside the test body is still pending, so it only waits for the one promise it is given. ## The three correct forms | Form | How the test is written | What Jest waits for | |---|---|---| | Returned promise | `return fetchJson(get, url).then(body => { expect(body)... })` | the promise returned by `.then` | | `async` / `await` | `async () => { const body = await fetchJson(get, url); expect(body)... }` | the promise the `async` function returns, which settles after the last `await` | | Awaited modifier | `await expect(fetchJson(get, url)).resolves.toEqual(...)` | the assertion promise that `.resolves` or `.rejects` produces | The Jest documentation describes `async` and `await` as syntactic sugar for the same logic as the returned-promise form, and says none of the forms is superior; many teams standardise on `async` / `await` because a missing `await` is easier to spot than a missing `return`. Note that **marking the function `async` is not enough by itself**. The promise an `async` function returns settles when the body finishes, and the body finishes at once if the call inside it is not awaited. `async () => { fetchJson(get, url).then(...) }` has exactly the same problem as the version without `async`. ## What happens when you forget Take a test that calls `fetchJson(get, '/users/7').then(body => expect(body).toEqual({id: 7}))` and returns nothing. The sequence is: 1. Jest calls the test function, which starts the request and attaches the `then` callback. 2. The function returns `undefined`, so Jest **stops waiting** and settles the test without the `then` callback's outcome. 3. Later, the promise settles and the `then` callback runs its `expect`. If that late `expect` fails, it throws inside a promise callback that no test is waiting for. Depending on timing, the failure may still be attributed to the test before the file finishes, may surface as an unhandled error outside any test (which can take the worker down with it), or may never be reported at all, because the file's tests have already completed. Whichever happens, the test's verdict no longer depends on the code it was written to check, which is the whole point of having it. ## The timeout is the safety net on the other side Waiting correctly has its own failure mode: a promise that never settles. Jest does not hang forever. Each test runs under a timeout, **5000 ms by default**, after which it fails with a message such as `Exceeded timeout of 5000 ms for a test.` A single long-running test can raise its own limit with a third argument to `test`, for example `test('slow import', async () => {...}, 20_000)`. Raising the limit is the fix only when the work is genuinely slow; when the promise is stuck, a bigger number just makes the failure arrive later. ## Habits that keep async tests honest - Write async tests as `async` functions and **`await` every promise** whose outcome you assert on, including every `expect(...).resolves` and `expect(...).rejects` chain. - Prefer `await expect(promise).rejects...` to a `try` / `catch` around the call, because the modifier fails the test when the promise unexpectedly fulfils. - Where an assertion has to live inside a callback, add `expect.assertions(n)` so a test whose callback never ran fails instead of passing. - When a new async test passes on its first run, **break the code under test on purpose** and watch the test fail. A test that cannot fail is the symptom this whole topic is about.

  • Is marking the Jest test function async enough on its own?
    No. `async` only makes the function return a promise, and that promise settles when the body finishes. If the body calls `fetchJson(...).then(...)` without `await`, the body finishes immediately and Jest stops waiting before the assertion runs. You must `await` the call, or the `expect(...).resolves` / `.rejects` chain, for its outcome to belong to the test.
  • What does Jest 30 report when an awaited promise never settles?
    The test fails when its timeout expires, 5000 ms unless configured otherwise, with `Exceeded timeout of 5000 ms for a test.` A test that is legitimately slow can pass its own limit as the third argument to `test`; a stuck promise needs fixing, not a bigger number.
  • What happens if a Jest test function returns a value that is not a promise?
    Jest 30 fails it with `test functions can only return Promise or undefined.` and prints the returned value. It typically happens with a concise arrow body such as `() => someValue`, where the expression's result becomes the return value.

  • Marking the test function async is enough; awaiting the calls inside is optional.
  • Jest waits for every promise the code under test creates, returned or not.
  • A green tick means every assertion in the test body actually ran.
  • A promise that never settles makes the Jest run hang forever.
  • Raising the test timeout fixes a test that does not wait for its promise.
open as a page

How do you turn on code coverage in a Jest 30 run, and what does Jest write out by default?

level: juniorimportance: must knowfreq 50%

basics

~10 s

Run jest --coverage or set collectCoverage: true. Jest then prints a per-file text table and writes clover, json and lcov reports, the lcov one including an HTML site, into a coverage folder under rootDir.

open as a page

In Jest 30, what does a jest.fn() mock function record about its calls, and which matchers read that record back?

level: juniorimportance: must knowfreq 76%

basics

~20 s

A jest.fn() mock records every call on its mock property: arguments in mock.calls, outcomes in mock.results, plus this values and instances. Matchers such as toHaveBeenCalledTimes and toHaveBeenCalledWith read that record; Jest 30 removed aliases like toBeCalled.

open as a page

In Jest 30, what is the default testEnvironment, and what do you change so a React component test can use document?

level: juniorimportance: must knowfreq 62%

basics

~10 s

Jest 30 defaults testEnvironment to node, so document and window do not exist. Install jest-environment-jsdom, then set testEnvironment: 'jsdom' in the config or add a @jest-environment jsdom docblock to that test file.

open as a page

In Jest 30, where does toMatchSnapshot store a snapshot, and how is each entry in that file named and matched?

level: juniorimportance: must knowfreq 58%

basics

~20 s

toMatchSnapshot serializes the value and stores it in snapshots/<test file>.snap beside the test, keyed by the full test name plus a counter; every later run serializes again and compares against the entry under that same key.

open as a page

In a Jest 30 test, how do toBe, toEqual and toStrictEqual differ when the value under test is an object or an array?

level: juniorimportance: must knowfreq 85%

basics

~10 s

toBe checks identity with Object.is, so two separately built objects never match. toEqual compares recursively but ignores undefined-valued keys, array sparseness and class type; toStrictEqual compares recursively and checks all three.

open as a page

In Jest 30, why does toThrow need the call wrapped in a function, and what arguments narrow the expected error?

level: juniorimportance: must knowfreq 70%

basics

~20 s

toThrow has to call the code itself to catch the error; an unwrapped call throws before expect even runs. Pass a substring, a regex, an error class (instanceof) or an error object (equal message) to narrow the match.

open as a page

In Jest 30, what do jest.useFakeTimers, advanceTimersByTime, runAllTimers and runOnlyPendingTimers each do to code waiting on setTimeout?

level: middleimportance: must knowfreq 60%

basics

~20 s

jest.useFakeTimers swaps setTimeout, setInterval, Date and related APIs for a fake clock that moves only on command. advanceTimersByTime moves it by a duration, runAllTimers runs until no timers remain, and runOnlyPendingTimers runs just the timers already queued.

open as a page

In Jest 30, how do the .resolves and .rejects modifiers work, and what must a test do with the assertion they produce?

level: middleimportance: must knowfreq 65%

basics

~20 s

In Jest 30, .resolves unwraps a fulfilled value and .rejects unwraps a rejection reason so any matcher can check it, failing if the promise settles the other way. The chain is a promise, so the test must await or return it.

open as a page

Why does a source file that no test imports never show up in a Jest 30 coverage report, and how does collectCoverageFrom change that?

level: middleimportance: must knowfreq 40%

basics

~20 s

Without collectCoverageFrom, Jest reports only files the tests loaded, so an untested module is invisible and the totals look better than they are. Listing source globs in collectCoverageFrom adds every matching file, at zero when nothing ran it.

open as a page

In Jest 30, what separates mockClear, mockReset and mockRestore, and which config keys run their all-mocks forms before every test?

level: middleimportance: must knowfreq 72%

basics

~10 s

mockClear empties the call record; mockReset also removes implementations, so the mock returns undefined; mockRestore also puts a jest.spyOn original back. clearMocks, resetMocks and restoreMocks run clearAllMocks, resetAllMocks and restoreAllMocks before each test.

open as a page

In Jest 30, how does jest.spyOn(object, methodName) differ from assigning jest.fn() to that method, and how is the original put back?

level: middleimportance: must knowfreq 66%

basics

~20 s

jest.spyOn swaps object[methodName] for a mock that records calls and, by default, still runs the original; mockRestore or jest.restoreAllMocks puts the original back. Assigning jest.fn() loses the original, so restoring it is the test's own job.

open as a page

In Jest 30, what is the difference between setupFiles and setupFilesAfterEnv, and what can code in each one use?

level: middleimportance: must knowfreq 58%

basics

~20 s

Both run before every test file. setupFiles runs first, inside the environment but before the test framework is installed, so expect, test and the hooks are undefined; setupFilesAfterEnv runs next and can call expect.extend or register afterEach.

open as a page

In Jest 30, how do you update snapshots after an intentional change, and what does jest -u actually rewrite or remove?

level: middleimportance: must knowfreq 62%

basics

~20 s

Run jest -u (--updateSnapshot): it re-records every snapshot that fails in that run, writes missing ones and deletes obsolete entries and orphaned .snap files, so narrow the run with a path pattern or -t first and review the diff.

open as a page

In Jest 30, how do toMatchObject and asymmetric matchers such as expect.objectContaining and expect.any assert only part of a result?

level: middleimportance: must knowfreq 60%

basics

~20 s

toMatchObject passes when the received object holds the expected properties, recursively, ignoring extras. Asymmetric matchers such as expect.any(Date) or expect.stringMatching(/^q_/) stand in for a single value inside toEqual or toMatchObject, so volatile fields need no exact value.

open as a page

In Jest 30, how do you make a jest.fn() mock return different values on successive calls, such as a charge that fails once then succeeds?

level: juniorimportance: should knowfreq 60%

basics

~20 s

Chain the Once helpers, such as mockRejectedValueOnce then mockResolvedValueOnce: each queues one result, consumed in order. When the queue is empty the mock falls back to its default from mockReturnValue, mockResolvedValue or mockImplementation, or returns undefined.

open as a page

In a Jest 30 test, how does the done callback work, and what goes wrong when it is misused?

level: middleimportance: should knowfreq 40%

basics

~20 s

A Jest 30 test that declares a parameter, conventionally done, is not finished until done() is called; done(error) fails it. Never calling done is a timeout, calling it twice is an error, and returning a promise as well is rejected.

open as a page

A Jest 30 service shows 92% line coverage yet an untested error branch shipped a bug; how do you find such branches in its Istanbul HTML report?

level: middleimportance: should knowfreq 30%

basics

~20 s

Open coverage/lcov-report/index.html, sort by the Branches column, and open the weak file. The babel provider marks an untaken if path with I and an untaken else with E, highlights other missed branches in yellow and shades unrun statements pink.

open as a page

How does Jest 30's coverageThreshold read a positive versus a negative number, and how are global, path and glob keys applied?

level: middleimportance: should knowfreq 35%

basics

~20 s

A positive coverageThreshold value is a minimum percentage; a negative one is the most uncovered items allowed. A directory key pools its files, a glob key checks each file alone, and global covers the files no other key matched.

open as a page

In a Jest 30 test file, why does jest.mock(path, factory) apply before the imports above it, and what limits does that set on the factory?

level: middleimportance: should knowfreq 58%

basics

~20 s

babel-jest hoists jest.mock above the file's imports, so every importer gets the mock. The factory may use only its own locals, allowed globals, pure constants and names prefixed mock, and a mock-prefixed variable must be initialised before the factory first runs.

open as a page

In a Jest test suite, why does importing '@/lib/price' or a .css file fail when the app builds fine, and how does moduleNameMapper fix it?

level: middleimportance: should knowfreq 50%

basics

~10 s

Jest resolves modules itself and reads neither the tsconfig paths nor the bundler's aliases and CSS loaders. moduleNameMapper maps request regexes to replacements, such as '^@/(.*)$' to '<rootDir>/src/$1' and '\.css$' to a stub module.

open as a page

In Jest 30, how does the transform option decide which tool compiles a TypeScript or JSX test file?

level: middleimportance: should knowfreq 45%

basics

~20 s

transform maps file-path regexes to transformers. With no transform key, Jest 30 uses babel-jest for .js, .jsx, .ts and .tsx files; once you set transform, that default is gone, so you list babel-jest, ts-jest or @swc/jest yourself.

open as a page

In Jest 30, how does toMatchInlineSnapshot write its snapshot into the test file, and what stops Jest from writing it?

level: middleimportance: should knowfreq 35%

basics

~20 s

On the first run Jest serializes the value, finds the toMatchInlineSnapshot call in the test source and inserts the text as a template-literal argument. It refuses in CI mode, and fails when one call site would need more than one value.

open as a page

In Jest 30, how do you snapshot an object holding a generated id and a timestamp without the snapshot failing on every run?

level: middleimportance: should knowfreq 45%

basics

~20 s

Pass property matchers as the first argument, such as toMatchSnapshot({id: expect.any(String), createdAt: expect.any(Date)}): Jest checks those fields against the matchers, stores the matcher in the snapshot instead of the value and compares the rest exactly.

open as a page

In a Jest 30 test file, when do describe callbacks run, and how do test.only, test.skip, test.todo and test.each change what runs?

level: middleimportance: should knowfreq 50%

basics

~20 s

Jest runs every describe callback first, synchronously, to collect tests, then runs them. test.only focuses tests within that file, test.skip marks one skipped, test.todo records a body-less placeholder, and test.each generates a test per data row.

open as a page

A Jest 30 test of a fetch wrapper's 500 branch asserts inside a catch block, yet passes when the wrapper succeeds. Why, and how do expect.assertions and expect.hasAssertions catch it?

level: seniorimportance: should knowfreq 55%

basics

~20 s

When the wrapper succeeds, the catch block never runs, no assertion executes, and Jest passes a test that ran no assertions. expect.assertions(n) fails it unless exactly n assertions ran; expect.hasAssertions() fails it unless at least one did.

open as a page

A Jest 30 test of an async retry helper calls jest.advanceTimersByTime(2000), yet the second attempt never runs. Why, and how do the Async timer methods fix it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

The helper only schedules its setTimeout after the awaited attempt settles, and the synchronous advance runs before any promise callback can, so it finds no timer to fire. Awaiting jest.advanceTimersByTimeAsync lets promise callbacks run before and between the timers.

open as a page

After a Jest 30 suite switched coverageProvider from babel to v8, every percentage moved and the threshold broke; what differs between the two providers?

level: seniorimportance: should knowfreq 25%

basics

~20 s

The default babel provider inserts Istanbul counters into each file during the transform; the v8 provider converts the engine's own block coverage. They count statements and branches differently, so figures and ignore comments do not carry over.

open as a page

Why would a Jest 30 order-service test pass alone but fail after the other tests in its file, and how do you trace and fix the leftover mock state?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Mocks live for the whole test file, so call records, unused Once values, implementations and installed spies carry into later tests. Reproduce with --randomize and a seed, compare the mock's state, then reset in beforeEach or enable clearMocks with restoreMocks.

open as a page

In a Jest 30 suite, why does a test that imports an ESM-only package from node_modules fail to load, and how do you fix it?

level: seniorimportance: should knowfreq 48%

basics

~20 s

transformIgnorePatterns defaults to skipping /node_modules/, so the package's import and export syntax is never compiled and loading it as CommonJS fails. Allowlist it, for example '/node_modules/(?!(package-a)/)', or on Node 24.9+ run Jest with --experimental-vm-modules to require() it natively.

open as a page

showing 1–30 of 36