Skip to content
Latchkey

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.

Vitest
⎯⎯⎯ 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:5432

Common 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

  1. Await or cancel every async operation a test starts.
  2. Clear timers and remove listeners in afterEach.
  3. Mock network calls so nothing connects after the test.
src/test/setup.ts
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.

src/load.test.ts
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.

Frequently asked questions

What causes ""Unhandled Error" outside of tests"?
A fire-and-forget async call (a fetch, a DB connect) rejects once the test has already resolved, surfacing as an unhandled rejection.
How do I fix "Unhandled Error" outside of tests?
Clean up async work in teardown

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card