skip to content

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

level: middleimportance: should knowfreq 40%

answer

  1. a declared parameter changes the mode
  2. wait until done is called
  3. a throw skips the done call
  4. done or a promise, never both

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.

solid answer

~50 s

Jest checks whether the test function declares a parameter. If it does, Jest passes in `done` and waits until it is called: `done()` passes the test, `done(error)` fails it with that error. The traps follow from that. An `expect` that throws inside the async callback skips the `done()` call, so the test waits until the 5-second timeout fails it with ``Exceeded timeout of 5000 ms for a test while waiting for `done()` to be called.``; wrap the assertion in `try` / `catch` and pass the error to `done(error)` to fail fast with the real message. Calling `done` twice fails with `Expected done to be called once, but it was called multiple times.` An `async` test that also takes `done` fails with `Test functions cannot both take a 'done' callback and return something.` Today `done` is mostly for callback-only APIs; wrapping them in a promise is usually cleaner.

code

javascript · 28 lines
javascript
function loadUser(id, callback) {
  setTimeout(() => {
    if (id < 0) callback(new Error('Server error 500'));
    else callback(null, {id});
  }, 10);
}

test('loads a user through a callback', done => {
  loadUser(7, (error, user) => {
    if (error) {
      done(error);
      return;
    }
    try {
      expect(user).toEqual({id: 7});
      done();
    } catch (assertionError) {
      done(assertionError);
    }
  });
});

test('the same check without done', async () => {
  const user = await new Promise((resolve, reject) => {
    loadUser(7, (error, value) => (error ? reject(error) : resolve(value)));
  });
  expect(user).toEqual({id: 7});
});

go deeper

for a junior

Recall that declaring done makes Jest wait for done() to be called, and that done(error) fails the test.

for a middle

Explain the timeout when an expect throws before done, the double-call error, and why done plus a returned promise is rejected.

for a senior

Migrate callback-style tests to promise wrappers and catch leftover done parameters that turn refactored tests into timeouts.

for a principal

Decide whether done stays allowed in the suite at all, given that promise-based tests report failures without per-assertion wrapping.

## How Jest switches into callback mode Before promises were common, asynchronous JavaScript reported completion by calling a function. Jest supports that style through a **`done` callback**. The switch is the test function's **declared parameter count**: Jest's runner treats any test function with at least one declared parameter as callback-style (in the jest-circus source the check is simply `fn.length > 0`). The name `done` is a convention; the parameter's presence is what counts. Once in that mode, Jest: - passes a callback as the first argument; - keeps the test open until that callback is called, however long the body takes; - passes the test on `done()` and fails it on `done(reason)`. An `Error` reason is reported as that error; anything else is reported as `Failed:` followed by the printed value, for example `Failed: "boom"`; - fails the test if the timeout expires first: 5000 ms by default, with a message that says it was waiting for `done()`. ## The failure modes | Mistake | What Jest 30 reports | |---|---| | `done` is never called | ``Exceeded timeout of 5000 ms for a test while waiting for `done()` to be called.`` | | an `expect` throws inside the callback before `done()` | the test still waits out the timeout, because `done()` was skipped | | `done` is called twice | `Expected done to be called once, but it was called multiple times.` | | the function takes `done` **and** returns a value, including an `async` function's promise | `Test functions cannot both take a 'done' callback and return something. Either use a 'done' callback, or return a promise.`, raised once `done` is called; if it never is, a timeout | | a `done` parameter is declared but never used | a timeout, since the declared parameter alone switches the test into callback mode | The second row deserves attention. A failing `expect` **throws**, so the line after it, the `done()` call, never runs, and the test hangs until the timeout. The Jest documentation warns that this can leave you with an opaque timeout error that does not show what value the assertion received. The fix is to catch the assertion error and hand it to `done`: ```js try { expect(user).toEqual({id: 7}); done(); } catch (assertionError) { done(assertionError); } ``` The last row comes up during refactoring: someone converts a callback test to `async`/`await` and leaves the parameter in the signature. The Jest documentation calls the done-plus-promise check a precaution against memory leaks in tests. ## Why most new tests avoid done Callback mode puts the burden of reporting failures on the test author: every error path has to reach `done(error)`, and every assertion has to be wrapped so it does not throw past the `done()` call. A promise-based test gets the same guarantees for free, because a thrown assertion rejects the promise Jest is already waiting on. So the usual advice is: 1. If the code under test returns a promise, use `async` / `await` and `.resolves` / `.rejects`; `done` adds nothing. 2. If it only takes a callback, **wrap the call in a promise** inside the test: `await new Promise((resolve, reject) => loadUser(7, (err, user) => (err ? reject(err) : resolve(user))))`, then assert on the result. One wrapper replaces every `try` / `catch` around `done`, and the error-first convention maps directly onto `reject` and `resolve`. If the same callback API is used in many tests, put the wrapper in a small helper next to the tests so each test reads like any other promise-based one. 3. Keep `done` for the rare case where completion is signalled by an event with no natural promise around it, and even then put `try` / `catch` around each assertion. ## Interaction with other guards - `expect.assertions(n)` still works in callback mode and is useful when a callback might never fire; but a callback that never fires also means `done` is never called, so the timeout catches that case anyway. - `done` and fake timers do not conflict: a callback scheduled with `setTimeout` under fake timers runs when the test advances the clock, and the test can call `done` from inside it. - `done` belongs to the test or hook it was passed to. Calling it after the test has finished does not reopen the test; when it carries an error at that point, Jest raises an error whose message begins `Caught error after test environment was torn down`.

  • Why does a Jest test with an unused done parameter time out even though its assertions pass?
    Jest decides on callback mode from the function's declared parameter count, not from whether the body uses the parameter. With `done` in the signature, Jest waits for it to be called; since nothing calls it, the test fails at the timeout with a message saying it was waiting for `done()`. Remove the parameter, or call `done()` at the end.
  • What does Jest 30 report when done is called with a string instead of an Error?
    The test fails, and the reason is printed after `Failed:`, so `done('boom')` produces `Failed: "boom"`. An `Error` passed to `done` is reported as that error with its own message and stack, which is why `done(error)` with the real error object gives the more useful report.

  • Jest decides on callback mode from the parameter's name being done.
  • A failing expect inside the callback fails the test immediately with its message.
  • An async test can take done as well, to be safe.
  • Calling done twice is harmless; Jest ignores the second call.
  • Removing done from an async test changes nothing, since Jest awaits either way.