Memory Leak in Long Test Suite
Error message
JavaScript heap out of memory — test suite too large
Quick summary
The test suite consumes too much memory, causing Node.js to crash with an out-of-memory error. This happens with very large test suites or memory leaks.
Why this happens
Too many tests running in a single Jest worker process.
Memory leaks — objects not being garbage collected between tests.
Large objects (big arrays, DOM trees) retained in memory.
Mocks or spies accumulating without cleanup.
Default Node.js memory limit (usually 1.5GB) is too low.
Minimal example
// Large data array grows across tests
let bigData = [];
beforeEach(() => {
bigData.push(generateLargeObject()); // never cleared
});let bigData;
beforeEach(() => {
bigData = [generateLargeObject()]; // reset each time
});
afterEach(() => {
bigData = null; // allow garbage collection
});Reset data in beforeEach and clear references in afterEach to prevent memory accumulation.
How to diagnose
Run tests with --logHeapUsage to track memory growth.
Run smaller subsets of tests to find which tests leak memory.
Check for global variables or singletons that accumulate data.
Look for missing cleanup in afterEach hooks.
How to fix
Increase Node.js memory: node --max-old-space-size=4096 node_modules/.bin/jest.
Run tests in more workers: jest --maxWorkers=50% (spreads memory across processes).
Add proper cleanup in afterEach: clear arrays, restore mocks, reset modules.
Use jest.resetModules() in beforeEach to clear module cache.
Split large test files into smaller ones.
How to prevent
Always clean up in afterEach — clear data, restore mocks, reset modules.
Avoid global mutable state in tests.
Keep test files focused and reasonably sized.
Monitor memory usage in CI with --logHeapUsage.
Related Resources
Related Lessons
- Test Best Practices
Writing maintainable tests.