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

rejectOnTimeout单测报Expected one assertion to be called错误原因

代码问题分析与修复方案

你的代码存在两处核心问题,直接导致了单元测试报错,也不符合功能需求:

问题1:核心逻辑完全不符合超时要求

你当前的实现是等待原Promise状态变更完成后,才判断执行耗时是否超过阈值,完全没有提前触发超时的逻辑:

  • 如果原Promise一直处于pending状态,你返回的Promise也会永远pending,单元测试等不到状态变更就被强制终止,自然会抛出Expected one assertion to be called but received zero assertion calls的错误
  • 就算原Promise最终能完成,也会出现「明明已经到了超时时间,还要等原Promise跑完才返回拒绝态」的问题,和需求要求的「指定时间未完成就立刻返回拒绝态」完全不符

问题2:代码逻辑不规范

你在finally块中没有加分支判断,reject('timeout_error')会无条件执行,只是因为Promise状态一旦变更就无法修改才没影响前两个测试的结果,属于错误的写法。


正确实现代码

const rejectOnTimeout = (promise, ms) => new Promise((resolve, reject) => {
  // 注册超时回调,到点直接返回拒绝态
  const timeoutTimer = setTimeout(() => {
    reject('timeout_error');
  }, ms);

  // 原Promise完成后清除超时定时器,透传原有结果
  promise
    .then(res => {
      clearTimeout(timeoutTimer);
      resolve(res);
    })
    .catch(err => {
      clearTimeout(timeoutTimer);
      reject(err);
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 17:15:01