Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 30 ยท Asynchronous Code

Testing Promises and Async/Await

Test promises and async functions in Jest: return or await them, use resolves and rejects, avoid the forgotten-await trap, and count assertions with expect.assertions.

Most real JavaScript is asynchronous: fetching data, reading files, talking to a database. A test that calls such a function gets a promise back, and a promise is a value that is not finished yet. If the test function ends before the promise settles, Jest has no reason to wait, so the test goes green even if the real result would have been wrong.

This lesson shows the safe ways to test promises (return it, await it, or use resolves/rejects), how the "forgotten await" trap works, and how expect.assertions guards against it. You should know the matchers from Common Matchers and how thrown errors are tested in Errors and Custom Matchers.

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 tiny test runner and expect written in Node for this lesson. They reproduce the waiting behavior, but they are not Jest's source.

Four safe ways to wait

Return it return promise.then(...)
async and await The clearest style.
resolves Unwrap a fulfilled value.
rejects Unwrap a rejection.

Every one of them hands Jest a promise to wait for.

1 / 2

A function to test

We will test an async function that looks up a user. It resolves with an object for a valid id and rejects for an invalid one.

JavaScript
async function fetchUser(id) {
  if (id <= 0) {
    throw new Error('invalid id');
  }
  // imagine a network call here
  return { id, name: 'Ada' };
}

An async function always returns a promise: the return becomes fulfillment and a throw becomes rejection.

Style 1: return the promise

Jest waits for a promise that your test function returns.

JavaScript
test('loads Ada', () => {
  return fetchUser(1).then((user) => {
    expect(user.name).toBe('Ada');
  });
});

The word return is essential. Without it the function returns undefined, the test ends immediately and the assertions run after Jest has already recorded a pass.

Style 2: async and await

Mark the test function async. Jest waits for the promise that an async function returns, and await makes the code read in order:

JavaScript
test('loads Ada', async () => {
  const user = await fetchUser(1);
  expect(user.name).toBe('Ada');
});

This is the style to default to. For a rejection, either use try/catch or rejects (next).

Style 3: resolves and rejects

.resolves waits for the promise to fulfill and then lets you use any matcher on the value. .rejects does the same for a rejection:

JavaScript
test('resolves with a user', async () => {
  await expect(fetchUser(1)).resolves.toEqual({ id: 1, name: 'Ada' });
});

test('rejects for a bad id', async () => {
  await expect(fetchUser(0)).rejects.toThrow('invalid id');
});

Notice that the whole expect(...) expression is awaited (or returned). .resolves/.rejects produce a promise, and that promise must be given to Jest. If the promise unexpectedly fulfills when you wrote .rejects, the assertion fails, which is what you want.

The forgotten-await trap

Look closely at this test:

JavaScript
test('loads Grace', () => {
  expect(fetchUser(1)).resolves.toEqual({ id: 1, name: 'Grace' }); // no await, no return
});

The expectation is wrong (the name is Ada), yet the test is reported as passed. The function finishes immediately, Jest records success, and the failing check happens later with nobody listening. The same thing happens with a promise chain whose return was forgotten, or an await missing in front of expect(...).rejects.

Two habits protect you:

  1. Always await or return anything that is a promise, including expect(...).resolves/rejects. Many teams enable a lint rule (for example jest/valid-expect) to catch this.
  2. Use expect.assertions or expect.hasAssertions when a test's checks sit in a place that might not run.

expect.assertions and hasAssertions

expect.assertions(n) fails the test unless exactly n assertions ran. expect.hasAssertions() fails unless at least one ran.

JavaScript
test('rejects with a helpful message', async () => {
  expect.assertions(1);
  try {
    await fetchUser(0);
  } catch (error) {
    expect(error.message).toBe('invalid id');
  }
});

Without expect.assertions(1), this test would pass silently if fetchUser(0) ever stopped rejecting, because the catch block would never run and there would be no failing check. The declared count turns "nothing was checked" into a failure. In many cases rejects is simpler and avoids the problem, but try/catch is useful when you want to look at several properties of the error.

Timeouts

If a promise never settles, the test waits and then fails with a timeout error (5 seconds by default; you can pass a third argument to test or call jest.setTimeout). A timeout is almost always a bug in the code under test, such as a callback that is never invoked or a request that never responds. Do not raise the limit as a first reaction. The next lesson, Callbacks and the done Callback, covers the older callback style.

A runner that waits (or does not)

The stand-in below has a test function that awaits whatever your test function returns, an expect with resolves and rejects, and support for expect.assertions. It also prints a message when an assertion fails after its test has already finished, which is exactly what you cannot see in a real run, where the test would simply show green.

Node.js Which async tests really wait?

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.

Read the output from the top. The late-failure lines may appear a little after the test they belong to, and they name it. The first four tests pass because they hand a promise to the runner. The fifth fails correctly. The sixth, with the forgotten await, is marked PASS even though its check was wrong, and a (late failure ...) line appears afterward. In a real Jest run you would not get that extra line, only the false green. Adding expect.assertions(1) converts it into a failure, as does the count in the last try/catch test.

Combining several async calls

Real tests often need more than one promise. Use Promise.all when the calls are independent, so the test does not take longer than necessary, and await them one after another when later calls depend on earlier results.

JS Independent versus dependent awaits

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

No output.

The values are identical, but the logs differ. In the sequential run each call starts after the previous one ends, so the waits add up (three times 30 ms). In the parallel run all three calls start first and their waits overlap (about 30 ms in total). In a test suite with many such calls, that adds up. For checking the values, toEqual([2, 4, 6]) works in either case.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can this test pass even when the expectation is wrong? test('x', () => { expect(getValue()).resolves.toBe(5); })

    The assertion produces a promise. If the test does not return or await it, Jest finishes the test before the check completes.
  2. 2. What does expect.assertions(2) do?

    It is a safety net that turns a skipped catch block or forgotten await into a failure.
  3. 3. Which test correctly checks that fetchUser(0) rejects with the message 'invalid id'?

    Only the third awaits the rejects assertion. The second throws before expect runs, because await turns the rejection into an exception. The first and fourth are not awaited or are using the wrong form.
  4. 4. When should you await promises one after another instead of using Promise.all?

    Independent calls can run together with Promise.all. Dependent calls must wait for each other.

Summary

  • Jest waits only for a promise it is given: return it, or use an async test function and await.
  • resolves and rejects unwrap a promise for ordinary matchers, but the whole expression must be awaited or returned.
  • A forgotten await produces a false green: the test ends first and the failing check happens unseen.
  • expect.assertions(n) and expect.hasAssertions() protect checks that might never run, such as those in a catch block.
  • Run independent async calls with Promise.all and dependent ones in sequence.

Next: Callbacks and the done Callback.