Vitest "Unhandled Error" / unhandled rejection outside tests in CI
Vitest reports errors that occur outside a test body, an unhandled promise rejection or a timer callback that throws after the test finished, as "Unhandled Errors" and fails the run. These come from async work that outlived the test. Clean up timers, listeners, and pending promises in teardown.
What this error means
The suite shows all tests passing but the run still fails with "Unhandled Errors" listing a rejection or a thrown callback that fired after the test completed.
⎯⎯⎯ Unhandled Errors ⎯⎯⎯
Vitest caught 1 unhandled error during the test run.
This might cause false positive tests. Resolve unhandled errors to make sure tests are not affected.
Error: connect ECONNREFUSED 127.0.0.1:5432Common causes
A promise rejects after the test ends
A fire-and-forget async call (a fetch, a DB connect) rejects once the test has already resolved, surfacing as an unhandled rejection.
A timer or listener outlives the test
A setTimeout or event handler that was never cleared fires later and throws outside any test.
How to fix it
Clean up async work in teardown
- Await or cancel every async operation a test starts.
- Clear timers and remove listeners in afterEach.
- Mock network calls so nothing connects after the test.
afterEach(() => {
vi.clearAllTimers()
vi.restoreAllMocks()
})Handle or assert on rejections
Await the promise and assert on its outcome so a rejection is caught inside the test, not after it.
await expect(loadData()).rejects.toThrow()How to prevent it
- Await or cancel every async operation before the test ends.
- Clear timers and listeners in afterEach.
- Mock external services so nothing connects post-test.