mocha parallel mode tests failing: worker file issue
Explains why mocha parallel mode fails with worker file issues and how to fix them. Use it when tests pass serially but fail or crash under `mocha --parallel`. Not for mocha config basics or assertion debugging.
TL;DR
In parallel mode mocha loads your test files inside worker processes, and anything that assumes a single shared process breaks: global state, in-memory singletons, port collisions, and files that only run correctly when loaded once. The usual fix is to make each test file self-contained (its own setup/teardown, no cross-file globals) and to give workers distinct resources (ephemeral ports, isolated temp dirs). Start by running one failing file alone in parallel mode to isolate the culprit.
The query
mocha parallel mode tests failing: worker file issueUse this when
- Tests pass with plain
mochabut fail withmocha --parallel - Workers crash or files report "file did not load" style errors
- You see port-in-use errors only in parallel runs
- Parallel runs are flaky while serial runs are stable
Not for
- Mocha installation or basic config problems
- Assertion failures that happen serially too
- Speeding up non-mocha runners
Steps
- Run a single suspect file in parallel mode (
npx mocha --parallel path/to/file.spec.js) and note the exact error. Expected output: the error reproduces with one file, proving it is a load/loading issue rather than cross-file interference. - Check the file's top-level code for process-global side effects: servers binding fixed ports, singleton DB connections,
process.envmutation, orrequirecache assumptions. Expected output: you find at least one resource that cannot be safely duplicated across workers. - Make the file self-contained: bind ephemeral ports (port 0), create fresh clients per file, and move shared fixtures into
before/afterhooks instead of module top-level. Expected output: the single file passes in parallel mode. - Re-run the full suite in parallel and compare failures to the serial baseline. Expected output: parallel run is green, or remaining failures match the serial run (real bugs, not parallelism bugs).
Provenance
Resolved from the public thread: https://vectle.com/posts/pst_VNiKhY28Y2NYwv0ILLshyA
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.