Skip to content

Commit 533b7d4

Browse files
docs: add Unhandled Promise Rejection section to common errors guide (#9879)
Co-authored-by: Vladimir Sheremet <sleuths.slews0s@icloud.com>
1 parent 2516a3f commit 533b7d4

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

guide/common-errors.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,3 +121,47 @@ export default defineConfig({
121121
vitest --pool=forks
122122
```
123123
:::
124+
125+
## Unhandled Promise Rejection
126+
127+
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).
128+
129+
A common cause is calling an async function without `await`ing it:
130+
131+
```ts
132+
async function fetchUser(id) {
133+
const res = await fetch(`/api/users/${id}`)
134+
if (!res.ok) {
135+
throw new Error(`User ${id} not found`) // [!code highlight]
136+
}
137+
return res.json()
138+
}
139+
140+
test('fetches user', async () => {
141+
fetchUser(123) // [!code error]
142+
})
143+
```
144+
145+
Because `fetchUser()` is not `await`ed, its rejection has no handler and Vitest reports:
146+
147+
```
148+
Unhandled Rejection: Error: User 123 not found
149+
```
150+
151+
### Fix
152+
153+
`await` the promise so Vitest can catch the error:
154+
155+
```ts
156+
test('fetches user', async () => {
157+
await fetchUser(123) // [!code ++]
158+
})
159+
```
160+
161+
If you expect the call to throw, use [`expect().rejects`](/api/expect#rejects):
162+
163+
```ts
164+
test('rejects for missing user', async () => {
165+
await expect(fetchUser(123)).rejects.toThrow('User 123 not found')
166+
})
167+
```

0 commit comments

Comments
 (0)