Testing async Promise-returning code in Jest
Whether you make async assertions actually run before the test ends.
Return or await the promise; use await expect(...).resolves/rejects, or await the value directly.
WHAT THIS TESTS: Whether you understand that Jest must be told when an async test is done, and whether you avoid the classic false-positive where a test passes because its assertions never actually ran.
A GOOD ANSWER COVERS: There are two main idioms. The async/await style: declare the test callback async, await the function, and assert on the resolved value with normal matchers; for rejections wrap in try/catch and use expect.assertions to guarantee the catch ran. The declarative matcher style: write await expect(fn()).resolves.toEqual(expected) for success, and await expect(fn()).rejects.toThrow(SomeError) for failure. The key invariant in both is that the promise must be returned or awaited so Jest does not end the test early. Older callback-style code can use the done callback, but it is error-prone and largely superseded.
COMMON WRONG ANSWERS: Calling the async function without awaiting or returning it, so the test resolves synchronously and reports green regardless of outcome. Using try/catch to test rejections but omitting expect.assertions(1), so if the function unexpectedly resolves, the catch never runs and the test still passes. Mixing done with an async callback.
LIKELY FOLLOW-UPS: How do you assert a promise rejects with a specific error type or message? Why is expect.assertions useful? When is the resolves/rejects form clearer than await? How do fake timers interact with pending promises?
ONE CONCRETE EXAMPLE: To test that fetchUser rejects for a missing id, write await expect(fetchUser(0)).rejects.toThrow('not found'). The await is essential; without it the returned promise is unhandled and the assertion is never observed, giving a misleading pass.
Read the original → jestjs.io
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.