Skip to content

Memory leak in long-running test suite

Quick summary

Your test suite leaks memory — objects, listeners, or connections accumulate and are not cleaned up between tests.

Why this happens

  • Event listeners or subscriptions are added in tests but not removed in cleanup

  • Large objects or caches are stored in module-level variables and never released

  • Database connections or network sockets are opened but not closed in afterEach

Minimal example

✗ Broken code
test('subscribes to updates', () => {
  emitter.on('update', handler); // listener added but never removed
  // each test adds a new listener — memory leak!
});
✓ Fixed code
afterEach(() => { emitter.removeAllListeners(); });
test('subscribes to updates', () => {
  emitter.on('update', handler);
  // listener removed in afterEach
});

Removing listeners in afterEach ensures each test starts with a clean emitter, preventing the memory leak.

How to diagnose

  • Monitor memory usage with process.memoryUsage() at intervals during the test run

  • Run tests in chunks to identify which tests cause memory growth

  • Use a memory profiler or heap snapshot to identify retained objects

How to fix

  • Add afterEach cleanup to remove listeners, close connections, and clear caches

  • Use weak references or limit cache size to prevent unbounded growth

  • Force garbage collection between test groups if the runtime supports it

How to prevent

  • Always clean up resources in afterEach — remove listeners, close connections, clear timers

  • Monitor memory usage in CI and fail the build if memory grows beyond a threshold

Related Resources

Related Glossary

Related Lessons

← Back to language