From fe9ed7ac857c2e3d44217f87ad78bc2f20c6b2be Mon Sep 17 00:00:00 2001 From: Srasti Jain Date: Thu, 19 Mar 2026 01:32:21 +0530 Subject: [PATCH] docs: add Unhandled Promise Rejection section to common errors guide (#9879) Co-authored-by: Vladimir Sheremet --- docs/guide/common-errors.md | 44 +++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/docs/guide/common-errors.md b/docs/guide/common-errors.md index e3808fb76..23a154ef7 100644 --- a/docs/guide/common-errors.md +++ b/docs/guide/common-errors.md @@ -121,3 +121,47 @@ export default defineConfig({ vitest --pool=forks ``` ::: + +## Unhandled Promise Rejection + +This error happens when a Promise rejects but no `.catch()` handler or `await` is attached to it before the microtask queue flushes. This behavior comes from JavaScript itself and is not specific to Vitest. Learn more in the [Node.js documentation](https://nodejs.org/api/process.html#event-unhandledrejection). + +A common cause is calling an async function without `await`ing it: + +```ts +async function fetchUser(id) { + const res = await fetch(`/api/users/${id}`) + if (!res.ok) { + throw new Error(`User ${id} not found`) // [!code highlight] + } + return res.json() +} + +test('fetches user', async () => { + fetchUser(123) // [!code error] +}) +``` + +Because `fetchUser()` is not `await`ed, its rejection has no handler and Vitest reports: + +``` +Unhandled Rejection: Error: User 123 not found +``` + +### Fix + +`await` the promise so Vitest can catch the error: + +```ts +test('fetches user', async () => { + await fetchUser(123) // [!code ++] +}) +``` + +If you expect the call to throw, use [`expect().rejects`](/api/expect#rejects): + +```ts +test('rejects for missing user', async () => { + await expect(fetchUser(123)).rejects.toThrow('User 123 not found') +}) +``` -- 2.51.2