Skip to content

Memory Leak in 长测试 Suite

错误信息

                JavaScript heap out 的 memory — 测试 suite 也大
              

快速摘要

测试 suite consumes 也 much memory, causing 节点.js 到 crash 使用 out-的-memory 错误. 这个 happens 使用 very 大测试 suites or memory leaks.

为什么发生

  • 也许多测试运行 in 单个 Jest 工作者处理.

  • Memory leaks — 对象不 是 garbage collected 之间测试.

  • 大对象 (大数组, DOM 树) retained in memory.

  • Mocks or spies accumulating 不使用 cleanup.

  • 默认节点.js memory 限制 (通常 1.5GB) 是也 低.

最小示例

✗ 错误代码
// 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 数据 in beforeEach and 清晰引用 in afterEach 到 prevent memory accumulation.

如何诊断

  • 运行测试使用 --logHeapUsage 到 track memory growth.

  • 运行 smaller subsets 的测试到 查找哪个测试 leak memory.

  • 检查 for 全局变量 or singletons 那个 accumulate 数据.

  • Look for missing cleanup in afterEach Hook.

如何修复

  • Increase 节点.js memory: 节点 --最大值-旧-空间-大小=4096 node_modules/.bin/jest.

  • 运行测试 in 更多工作者: jest --maxWorkers=50% (spreads memory 跨越处理).

  • 添加 proper cleanup in afterEach: 清晰数组, restore mocks, reset 模块.

  • Use jest.resetModules() in beforeEach 到清晰模块缓存.

  • 拆分大 测试 files 到 smaller ones.

如何预防

  • 总是 clean 上 in afterEach — 清晰数据, restore mocks, reset 模块.

  • Avoid 全局可变状态 in 测试.

  • Keep 测试 files focused and reasonably sized.

  • Monitor memory usage in CI 使用 --logHeapUsage.

相关资源

相关课程

← 返回语言