You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Jest所有测试通过却仍抛出内部错误?

问题分析与解决建议

问题描述

给代码新增功能后,运行所有Jest测试时控制台显示“全部测试套件已执行”,但Jest仍抛出内部错误,错误信息如下:

Ran all test suites.
the_path\node_modules\expect\build\index.js:303
      throw error;
      ^

JestAssertionError: expect(received).toBe(expected) // Object.is equality

Expected: "node-user-settings"
Received: "null"

单独创建另一个.js文件调用待测试代码时,Jest运行正常,无法理解为何测试代码会触发该错误。触发错误的测试代码如下:

test("asynchronously gets a value, using callbacks without optional filename", () => {
  settings.getState_c("moduleName", null, null, (err, data) => {
    expect(err).toBe(null);
    expect(data).toBe("node-user-settings");
  });
});

原因与解决思路

  • 异步测试未正确等待回调执行:Jest默认同步执行测试流程,测试函数会在回调触发前就结束,导致断言未被正确捕获,进而抛出异常。
  • 解决方法:
    • 使用done参数:给测试函数添加done参数,在回调逻辑执行完成后调用done(),通知Jest测试结束
      test("asynchronously gets a value, using callbacks without optional filename", (done) => {
        settings.getState_c("moduleName", null, null, (err, data) => {
          expect(err).toBe(null);
          expect(data).toBe("node-user-settings");
          done();
        });
      });
      
    • 改用Promise或async/await:如果能将getState_c包装为Promise,使用异步测试语法会更直观
  • 回调返回的data为null:需要排查getState_c函数在测试环境下的逻辑,确认传入null作为文件名参数时,是否正确返回了预期的"node-user-settings"值,可能是测试环境的配置或数据初始化问题导致返回null。

内容的提问来源于stack exchange,提问作者Noah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 05:25:15