Jest watch mode mock restoration configuration to prevent memory leaks
0 reputation · 11 Sept 2023, 18:22 UTC
0 reputation · 11 Sept 2023, 18:22 UTC
Goal: Keep Jest test suite memory consumption stable when running in watch mode while tests use mocked modules.
Constraint: Enabling restoreMocks guarantees each test starts with a clean module implementation but may add noticeable overhead because Jest deep‑clones modules; the current default keeps restoreMocksfalse to preserve speed.
Uncertainty: It is unclear whether the performance cost is acceptable in watch mode, where the Node process persists across test runs and leaks can accumulate, or whether an automatic opt‑in behavior should be introduced.
Should Jest automatically enable restoreMocks in watch mode to prevent memory leaks?
What level of performance impact would be considered acceptable for this safety guarantee?
Could a dedicated watch‑mode flag (e.g., watchRestoreMocks) provide a middle ground?
31775 reputation · 12 Sept 2023, 02:19 UTC
Jest does not automatically turn on restoreMocks when running in watch mode; you must enable it yourself if you want mock‑related state to be cleared between test runs.
restoreMockstrue causes Jest to deep‑clone each mocked module before every test, guaranteeing a clean implementation but adding CPU and memory work proportional to the mock size.Enabling restoreMocks in watch mode would stop mock‑related leaks because each test starts with a fresh clone, but the cloning cost is paid on every test pass. For small‑to‑medium mocks the overhead is usually modest; for large or numerous mocks it can become noticeable and slow down the feedback loop.
restoreMocks: true to your Jest configuration (e.g., jest.config.js).jest.watch.config.js) that sets restoreMocks: true and start Jest with jest --config jest.watch.config.js --watch.process.env.JEST_WATCH_MODE is not built‑in, so you can rely on a separate config file as shown above).restoreMocks:false) and monitor memory over several cycles (e.g., node --inspect or --detectOpenHandles). Note the baseline growth.restoreMocks:true (or the watch‑specific config) and compare memory growth and test execution time.jest --verbose or wrap jest.resetModules() in a timer to see the per‑run overhead.To decide whether the performance impact is acceptable, we need to know the approximate size or complexity of the modules you are mocking (e.g., number of lines, dependencies) and how frequently your test suite runs in watch mode. With that information you can judge if the clone overhead is negligible for your workflow.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.