Mocha async timeout precedence between global configuration and per-test overrides in ESM modules
0 reputation · 30 Dec 2021, 21:00 UTC
0 reputation · 30 Dec 2021, 21:00 UTC
Mocha 8+ introduced ESM module support that altered how asynchronous tests handle unhandled rejections and timeout enforcement. The framework applies a default 2000 ms timeout globally, while allowing per-suite and per-test overrides via this.timeout() or the --timeout CLI flag. The slow() threshold (default 75% of timeout) influences reporting but not failure behavior.
Documentation indicates that global timeout changes may affect test isolation if not properly scoped, and that the --timeout flag must precede test files in some versions. However, the exact precedence order when multiple configuration layers coexist—global default, CLI flag, suite-level this.timeout(), and test-level this.timeout()—remains underspecified for async/await tests in ESM contexts. Node.js version differences further complicate unhandled rejection handling during timeout expiration.
What is the documented precedence order for timeout values across global, CLI, suite, and test levels when using async/await in ESM modules? Does a test-level this.timeout() call reliably override a CLI-provided --timeout value? How do unhandled rejections interact with timeout expiration across Node.js 18, 20, and 22?
35775 reputation · 31 Dec 2021, 03:50 UTC
The documented precedence is: test‑level this.timeout() > suite‑level this.timeout() > CLI --timeout flag (or global config) > Mocha’s built‑in default of 2000 ms.
function() test callback so that this refers to the Mocha test context; arrow functions do not bind this and the call is ignored.slow() threshold is purely for reporting and does not affect pass/fail or timeout enforcement.test/timeout.mjs with a suite and a test:import { describe, it } from 'mocha';
describe('timeout suite', function () {
this.timeout(150); // suite‑level
it('should respect test timeout', function () {
this.timeout(50); // test‑level
return new Promise(res => setTimeout(res, 200)); // longer than test timeout
});
});
mocha --timeout 500 test/timeout.mjsIf you need to confirm that unhandled rejections are not being converted to timeouts on your Node version, run node --version and mocha --version and check whether --unhandled-rejections=strict or similar flags are in effect; this can change whether a rejected promise aborts the process before Mocha’s timeout fires.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.