Unhandled Promise Rejection in Test
Error message
UnhandledPromiseRejectionWarning: Error in test
Quick summary
An async operation rejected (threw an error) but the test didn't catch it. This can cause the test to pass incorrectly or crash unexpectedly.
Why this happens
An async function rejects but the test doesn't use try/catch or .rejects.
A Promise is created but not awaited or returned, so the rejection is unhandled.
A mock is set up with mockResolvedValue but the code calls a rejecting function.
Missing await on an async call that can reject.
Minimal example
test('handles error', async () => {
// Missing rejection handling
const result = await fetchData(); // if this rejects, unhandled
expect(result).toBeDefined();
});test('handles error', async () => {
await expect(fetchData()).rejects.toThrow('Network error');
});Use .rejects.toThrow() to properly handle and test Promise rejections.
How to diagnose
Look for async operations without await or .catch().
Check if mocks are set up to reject when the test expects success.
Use expect.assertions(1) to ensure the test actually runs assertions.
Add try/catch or use .rejects.toThrow() for expected rejections.
How to fix
For expected rejections: await expect(asyncFn()).rejects.toThrow('error message').
Or use try/catch: try { await asyncFn(); fail('should have thrown'); } catch (e) { expect(e.message).toBe('...'); }
Ensure all Promises are awaited or returned from the test.
Fix mock setup to match the expected behavior (resolve vs reject).
How to prevent
Always await or return Promises in tests.
Use .rejects.toThrow() for testing expected rejections.
Enable --unhandled-rejections=strict in Node.js to catch these early.
Related Resources
Related Lessons
- Async Testing
Testing asynchronous code.