Test fails due to unhandled promise rejection timing issue.
The issue involves a test failing due to promise rejection timing with setTimeout. The behavior suggests an async timing problem in test execution. While the reproduction is clear, the fix may require understanding Node.js's promise rejection handling internals.
v25.0.0
Linux Federation 6.17.0-19-generic #19~24.04.2-Ubuntu SMP PREEMPT_DYNAMIC Fri Mar 6 23:08:46 UTC 2 x86_64 x86_64 x86_64 GNU/Linux
promises + timeouts
The following test always fails:
./Trivial.js
"use strict";
// Happens with `const { setTimeout } = require("node:timers/promises");`, too
const setTimeout = (t) => new Promise((resolve) => globalThis.setTimeout(resolve, t));
async function main() {
const badPromise = Promise.reject("bad value");
console.debug("Promise created");
await setTimeout(100);
console.debug("Timeout awaited");
try {
console.debug("Awaiting promise");
await badPromise;
throw new Error("should not resolve");
} catch (error) {
console.debug("Task failed successfully:", error);
}
};
main();
Every time.
The trivial test should pass.
Trivial test runs fully, but reports as having failed before its execution ends, despite the rejected promise being awaited within a try/catch block.
output:
Fordi@the-laptop:~/develop/trivial-failure$ node --test Trivial.cjs
Promise created
node:internal/process/promises:330
new UnhandledPromiseRejection(reason);
^
UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "bad value".
at throwUnhandledRejectionsMode (node:internal/process/promises:330:7)
at processPromiseRejections (node:internal/process/promises:413:17)
at process.processTicksAndRejections (node:internal/process/task_queues:104:32) {
code: 'ERR_UNHANDLED_REJECTION'
}
Node.js v25.0.0
This situation i
Claim this issue to let others know you're working on it. You'll earn 15 points when you complete it!