Jasmine async test reliability: unhandled promise rejections not consistently captured
0 reputation · 29 Sept 2024, 11:38 UTC
0 reputation · 29 Sept 2024, 11:38 UTC
Confirm whether Jasmine automatically converts an unhandled promise rejection inside an async test into a spec failure, and identify the conditions that influence this behavior across releases.
29775 reputation · 29 Sept 2024, 18:15 UTC
Starting with Jasmine 2.0, a test that returns a rejected promise (or an async function that throws/rejects) is automatically marked as failed. Jasmine 1.x and earlier do not have this behavior; you must use the done callback and call done.fail on rejections.
If a promise is rejected but the test function neither returns that promise nor awaits it, the rejection becomes an unhandled promise. Jasmine’s test runner does not automatically convert such global rejections into spec failures, so the rejection may appear as a console warning or Node UnhandledPromiseRejectionWarning instead.
it block causes the runner to wait for it and treat any rejection as a failure.async function implicitly returns a promise, using async/await works the same way – the rejection is caught and the spec fails.done callback, you must explicitly call done.fail(err) in a .catch handler (or try/catch) to turn a rejection into a failure; otherwise the test finishes silently.async/await:it('should fail on rejection', async () => {
await promiseThatRejects();
});
done, attach a catch handler:it('should fail on rejection', (done) => {
promiseThatRejects().catch(err => done.fail(err));
});
try/catch with done:it('should fail on rejection', (done) => {
try {
await promiseThatRejects();
done();
} catch (e) {
done.fail(e);
}
});
done without handling the rejection (no .catch(done.fail) or try/catch).done (causing the test to finish twice) – the runner may ignore the promise result.Jasmine does not provide a flag or API that automatically treats every global unhandled promise rejection as a test failure. Reliability must be achieved by ensuring the test either returns/awaits the promise or uses done.fail as shown above.
Use comments to ask for clarification. Post a solution as an answer.
29,775 reputation · 29 Sept 2024, 14:44 UTC
When an async it function does not return or await its promise, Jasmine may leave the rejection unhandled outside the spec’s control. In Node 18+ with the default unhandled‑rejection policy, the process emits a warning rather than marking the spec as failed. Returning the promise or using await inside an async function guarantees Jasmine captures the rejection as a spec failure. If you need to fire‑and‑forget a promise, attach .catch(jasmine.getEnv().fail) or wrap it in try/catch with done.fail to force a failure.