Jest测试用例失败时执行速度异常缓慢问题求助
Jest失败测试执行耗时异常问题
场景复现
测试文件代码
import Client from "socket.io-client" describe("my awesome project", () => { let clientSocket; beforeAll((done) => { clientSocket = new Client(`http://localhost:3000`); clientSocket.on("connect", done); }); afterAll(() => { clientSocket.close(); }); it("should work", (done) => { clientSocket.on("redacted", (message) => { expect(2 + 2).toBe(56); //expect(message === "foobar").toEqual(true); done(); }); clientSocket.emit("redacted", "world"); }); });
这是一个POC(概念验证)项目,仅包含上述实现。
Jest配置文件
export default { // Automatically clear mock calls, instances, contexts and results before every test clearMocks: true, // Indicates whether the coverage information should be collected while executing the test collectCoverage: true, // The directory where Jest should output its coverage files coverageDirectory: "coverage", // Indicates which provider should be used to instrument code for coverage coverageProvider: "v8", // A preset that is used as a base for Jest's configuration preset: "ts-jest", };
配置文件由jest --init命令生成。
核心问题
- 测试通过时执行速度正常(如
expect(2 + 2).toBe(4)可快速完成) - 任何触发断言失败的测试,执行耗时异常夸张(曾运行过夜耗时14小时)
- 失败测试中Socket通信返回数据速度符合预期,卡顿仅发生在断言失败触发时,排除Socket通信环节问题
解决方案
1. 临时禁用覆盖率收集
当前配置开启了collectCoverage: true,断言失败时Jest可能在生成覆盖率报告时出现异常阻塞。修改jest.config.js:
collectCoverage: false,
重新运行失败测试,若耗时恢复正常,说明是覆盖率收集与失败测试的兼容性问题,可后续单独处理覆盖率生成(如仅在测试全通过时执行)。
2. 适配Jest与ts-jest版本
版本不匹配可能导致断言失败时的异常逻辑。先查看当前版本:
npm list jest ts-jest
升级到最新稳定版确保适配:
npm install jest@latest ts-jest@latest --save-dev
3. 重构异步测试逻辑
避免在回调中同时使用done()和失败断言,改用Promise/async-await模式:
it("should work", async () => { const messagePromise = new Promise(resolve => { clientSocket.on("redacted", resolve); }); clientSocket.emit("redacted", "world"); const message = await messagePromise; expect(2 + 2).toBe(56); // expect(message).toBe("foobar"); });
这种方式无需手动调用done(),Jest会自动处理异步流程,避免回调中失败断言导致的内部状态混乱。
4. 启用调试日志定位问题
添加参数运行测试,查看断言失败时的日志输出:
npx jest --verbose --logHeapUsage
通过日志排查是否存在内存泄漏或异常循环逻辑。
5. 调整Windows终端环境
- 使用独立终端(如PowerShell、Cmd)而非IDE内置终端运行测试
- 关闭终端快速编辑模式:右键终端标题栏 -> 属性 -> 取消勾选"快速编辑模式"
内容的提问来源于stack exchange,提问作者tracer tong
相关产品推荐
相关产品推荐

