100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Testing

Testing Async Code: Promises and async/await

Learn the correct patterns for testing promise-based and async/await code in Jest, and the pitfalls that let async bugs slip past a green test run.

Assertions & MatchersIntermediate9 min readJul 10, 2026
Analogies

Testing Asynchronous Code in Jest

By default, Jest considers a test finished as soon as its test function returns, which is a problem for asynchronous code: if a test kicks off a promise-returning operation but returns before that promise settles, Jest moves on to the next test without ever checking whether the async assertion passed or failed. A test can appear green even though the assertion inside a .then() callback actually failed, simply because the failure happened after Jest had already stopped watching. Jest supports several correct patterns for async code: returning the promise, using the resolves/rejects matchers, or using an async test function with await.

🏏

Cricket analogy: This resembles an umpire walking off the field before checking the third umpire's replay decision; the on-field call goes on record even if the replay would have overturned it, because no one waited for the result.

Testing Promises with return and resolves/rejects

The simplest fix is to return the promise from the test function; Jest will wait for the returned promise to settle before considering the test complete, and any assertion failure inside a .then() will properly fail the test. Jest also provides resolves and rejects modifiers that unwrap a promise's resolved or rejected value directly into a matcher, so expect(promise).resolves.toBe(value) or expect(promise).rejects.toThrow() reads cleanly without manual .then() chains, though the expect call itself must still be returned or awaited.

🏏

Cricket analogy: Returning the promise is like a captain formally requesting the third umpire review and staying to watch the big screen, rather than walking off assuming the on-field decision stands; the final call only counts once the review completes.

javascript
function fetchScore(matchId) {
  return fetch(`/api/matches/${matchId}/score`).then(res => res.json());
}

test('resolves with the correct score object (returning the promise)', () => {
  return fetchScore(1).then(score => {
    expect(score).toEqual({ home: 2, away: 1 });
  });
});

test('resolves matcher unwraps the value directly', () => {
  return expect(fetchScore(1)).resolves.toEqual({ home: 2, away: 1 });
});

Testing with async/await

Marking the test function itself async and using await is generally the clearest pattern: it reads like synchronous code, integrates naturally with try/catch for testing rejections, and works well alongside toThrow via rejects. Because await pauses execution until the promise settles, Jest automatically waits for the test function's returned promise (implicitly created by the async keyword) before moving on, so there's no risk of the test finishing before an assertion has actually run.

🏏

Cricket analogy: This resembles a batter waiting at the crease for the third umpire's decision to flash on the big screen before walking off, rather than guessing and leaving early; the wait is built into the process.

javascript
async function getUserProfile(id) {
  const res = await fetch(`/api/users/${id}`);
  if (!res.ok) throw new Error('User not found');
  return res.json();
}

test('async/await resolves with expected profile', async () => {
  const profile = await getUserProfile(42);
  expect(profile.id).toBe(42);
});

test('async/await handles rejection with rejects', async () => {
  await expect(getUserProfile(-1)).rejects.toThrow('User not found');
});

You can combine async/await with try/catch to make assertions about the error object itself, but expect(promise).rejects.toThrow(...) is usually more concise and less error-prone for the common case.

Common Pitfalls with Async Tests

The most common pitfall is forgetting to return or await the promise entirely, which silently defeats the whole test regardless of which pattern you started with; a test with an async assertion but no return/await keyword can pass even when the code is completely broken. Another pitfall is mixing the done callback (Jest's older async pattern) with returned promises or async/await in the same test, which is unsupported and produces confusing timeout errors; pick one pattern per test. Finally, remember that the default Jest test timeout is 5 seconds, so a genuinely slow async operation may need an explicit longer timeout passed as the third argument to test().

🏏

Cricket analogy: Forgetting to await is like a fielder appealing for a catch and walking off before the umpire's decision, celebrating a wicket that was never actually given; the outcome you assumed was never confirmed.

A test that never returns or awaits its promise can pass silently even when the underlying assertion fails, because Jest finishes the test before the promise settles. Always return the promise, await it, or return the expect(...).resolves/.rejects chain — never leave it dangling.

  • By default Jest finishes a test when the test function returns, not when its async work completes.
  • Return the promise, or make the test function async and await it, so Jest waits for the real result.
  • expect(promise).resolves.toEqual(...) and expect(promise).rejects.toThrow(...) unwrap promises directly.
  • async/await with try/catch or rejects is the clearest pattern for testing rejections.
  • Forgetting to return/await a promise is a top cause of tests that pass despite broken code.
  • Don't mix the legacy done callback with returned promises or async/await in the same test.
  • The default 5-second test timeout can be overridden as the third argument to test() for slow operations.

Practice what you learned

Was this page helpful?

Topics covered

#Testing#JestStudyNotes#TestingQA#TestingAsyncCodePromisesAndAsyncAwait#Async#Code#Promises#Await#Concurrency#StudyNotes#SkillVeris