I built jest-doctor, a custom Jest environment that detects async work leaking across test boundaries, one of the common causes of flaky tests.
These leaks usually come from unresolved promises, timers, or side effects that survive after a test finishes. Tests may pass locally but fail in CI or only fail when run together. Jest’s built-in --detectOpenHandles often misses these cases.
jest-doctor works by:
- tracking async resources created during each test (via async_hooks)
- patching globals like setTimeout and related APIs
- checking at test boundaries that resources were cleaned up
- failing the test immediately when leaks remain
It currently catches things like:
- unresolved promises
- open real or fake timers
- leaked DOM event listeners
- unexpected console or process output
The goal is to enforce test isolation so flaky failures become deterministic and easier to debug.
I’d really appreciate feedback from anyone who has fought flaky Jest tests, especially around edge cases where this approach might fall short.
Stephan_Dum•1h ago
There is also a feature request to include parts of in in jest itself: https://github.com/jestjs/jest/issues/15953
Happy to answer questions about flaky Jest tests or async leak detection.