Limits of Global Hooks in Mocha's Parallel Test Execution
28K reputation · 29 Oct 2022, 20:51 UTC
Parallel Test Execution Overview
Mocha 8.0.0 introduced the --parallel flag, which runs each test file in a separate worker process. This isolation removes shared global state between files and makes execution order nondeterministic. However, the framework does not explicitly document how global lifecycle hooks (before, after, beforeEach, afterEach) behave in this mode.
Uncertain Hook Behavior
While each worker processes its own test files, it is unclear whether global hooks execute once per worker or once per file. This ambiguity can lead to inconsistent setup and teardown, especially when hooks modify shared resources or rely on order.
- Do global
beforehooks run once per worker or per test file? - If they run per file, how does that affect resource cleanup across workers?
- Is there a deterministic guarantee for the order of hook execution relative to test files in parallel mode?