Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 30 ยท Asynchronous Code

Callbacks and the done Callback

Test callback-based code in Jest with the done argument, handle timeouts and errors, turn callbacks into promises with promisify, and learn why done is a legacy tool.

Before promises, JavaScript reported results through callbacks: readFile(path, (error, data) => { ... }). Plenty of code still works this way, including older Node APIs, event emitters and libraries you do not control. A test cannot simply call such a function and walk away, because the result arrives after the test function has returned.

Jest solves this with the done callback: if your test function declares a parameter, Jest passes in a function and waits until you call it. This lesson shows how that works, what a timeout means, why done is mostly a legacy tool, and how to wrap callback APIs in promises so you can use the cleaner style from Testing Promises and Async/Await.

Real versus stand-in. The Jest code in plain blocks is real but read-only, because the site cannot run Jest. The runnable examples use a small runner written in Node for this lesson. It copies the visible behavior (a done argument, a timeout) but it is not Jest's source.

How done works

Declare it The test takes a done parameter.
Jest waits Until done is called, or time runs out.
done() The test passes.
done(error) The test fails with that error.
1 / 2

A callback API to test

Imagine a small function that looks something up asynchronously and reports the result with a Node-style callback: the first argument is an error (or null), the second is the result.

JavaScript
function lookupPrice(sku, callback) {
  setTimeout(() => {
    if (sku === 'pen') {
      callback(null, 2.5);
    } else {
      callback(new Error(`unknown sku: ${sku}`));
    }
  }, 10);
}

The wrong way

JavaScript
test('finds the price of a pen', () => {
  lookupPrice('pen', (error, price) => {
    expect(price).toBe(2.5);   // runs later, after the test has finished
  });
});

The test function returns right away. Jest sees no promise and no done, so it declares success. The assertion runs about ten milliseconds later and nobody is checking. This is the callback version of the forgotten-await trap.

The right way: done

Add a done parameter and call it once the work is complete.

JavaScript
test('finds the price of a pen', (done) => {
  lookupPrice('pen', (error, price) => {
    try {
      expect(error).toBeNull();
      expect(price).toBe(2.5);
      done();
    } catch (assertionError) {
      done(assertionError);
    }
  });
});

Three rules to remember:

  1. Call done() exactly when everything is finished, not earlier. Call it after the last assertion.
  2. Call done(error) to fail, passing an error object. That is the only way to report a failure from inside the callback with a clear message.
  3. Wrap the assertions in try/catch. If an expect throws inside the callback, the exception happens in the middle of a timer or an event, not inside your test function. Depending on where the callback runs, you may get a confusing error or just a timeout instead of the assertion message. Catching it and calling done(error) guarantees a readable failure.

Timeouts

If done is never called, Jest waits and then fails the test with a message saying that the test exceeded its timeout (5 seconds by default). Typical causes:

  • The code path never calls the callback, for example on an error branch you did not expect.
  • An assertion threw before done() was reached.
  • A bug in your test: done was called in only one of two branches.

You can set the limit per test with a third argument, or for a file with jest.setTimeout(ms):

JavaScript
test('slow lookup', (done) => {
  // ...
}, 10000);

Raise the limit only when the code under test is truly slow. A timeout is usually a symptom of a missing done().

You cannot mix done with promises

A test either takes done or returns a promise (including being async), never both. Jest raises an error if you do both, because it would not know which one to trust:

JavaScript
// Not allowed: the function takes done AND is async
test('mixed', async (done) => {
  const price = await somethingAsync();
  done();
});

If you are using await, you do not need done at all.

Wrap callbacks in promises

Most of the time the better move is to avoid done by converting the callback API into a promise. Node's util.promisify does this for functions that follow the (error, result) convention:

JavaScript
import { promisify } from 'node:util';

const lookupPriceAsync = promisify(lookupPrice);

test('finds the price of a pen', async () => {
  await expect(lookupPriceAsync('pen')).resolves.toBe(2.5);
});

test('rejects for an unknown sku', async () => {
  await expect(lookupPriceAsync('ghost')).rejects.toThrow('unknown sku');
});

For APIs that do not follow that convention, such as an event emitter, write the wrapper yourself with new Promise:

JavaScript
function nextEvent(emitter, name) {
  return new Promise((resolve) => emitter.once(name, resolve));
}

The test then reads top to bottom, failures show the real assertion error, and a never-resolving wrapper becomes an ordinary timeout. We use this idea again for events in Project: Test an Event System.

Why done is a legacy tool

  • It needs extra ceremony (try/catch, calling done in the right place).
  • Forgetting a branch leads to a timeout rather than a message about the real problem.
  • It cannot be combined with async/await.

It remains useful for callback APIs that you cannot wrap, and you will see it in older code bases. In new code, convert to a promise at the edge and use async tests.

A runner with done and a timeout

The stand-in below runs a test function in the way Jest does: if it declares a parameter, it is given a done callback and the runner waits (with a short 80 ms limit here, so the example finishes quickly); otherwise it waits for the returned value. It also refuses a function that both takes done and returns a promise. Read each outcome against the rules above.

Node.js done, timeouts and mixed styles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first test is green although its assertion is wrong: the runner finished it before the 10 ms timer fired, and the stand-in prints the swallowed failure so you can see what a real run would hide. The third test shows done(assertionError) giving a clear message. The fourth shows what a missing done() looks like: a timeout, not an explanation. The mixed test is rejected before it runs, matching the real rule.

A second example: wrapping an event

Not every callback API follows the (error, result) convention. Here we wrap an event emitter so a test can simply await the event, and use a timeout so a missing event does not hang forever.

Node.js Turn an event into a promise

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In a Jest test the same helper reads as const [file] = await nextEvent(downloader, 'done'); expect(file).toBe('report.pdf');, with no done parameter and no try/catch.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A test calls a callback-based function but takes no done parameter and returns nothing. What happens?

    Without done or a returned promise, Jest has nothing to wait for. The test is recorded as passed before the callback fires.
  2. 2. Why wrap assertions in try/catch inside a done-style test?

    An exception inside an asynchronous callback does not reach the test function. Catching it and calling done(error) produces a clear failure.
  3. 3. A done-style test fails with a timeout. What is the most likely cause?

    A timeout means done was never called (or the promise never settled). Check every branch of the callback.
  4. 4. Which tool turns an (error, result) callback function into one that returns a promise?

    util.promisify wraps Node-style callback functions so you can await them or use resolves and rejects.
  5. 5. Can a test be declared async and also take a done parameter?

    Mixing the two is ambiguous, so Jest rejects it. With async and await you do not need done.

Summary

  • A test that fires a callback and returns nothing finishes before the callback runs; use done or a promise.
  • With done, call it after the final assertion, pass an error to fail, and wrap assertions in try/catch.
  • A timeout usually means done() was never reached.
  • A test may take done or return a promise, never both.
  • Prefer wrapping callback APIs with util.promisify or new Promise, then write an ordinary async test.

Next: Setup and Teardown Hooks.