skip to content

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.