You need to enable JavaScript to run this app. Jest测试异步校验中间件时,mock返回null触发indexOf未定义错误
优惠活动
大模型
产品
解决方案
定价
更多

Jest测试异步校验中间件时,mock返回null触发indexOf未定义错误

Jest测试执行触发isPendingSpecException报错 无法通过mock返回null覆盖分支逻辑

我正在使用Jest编写异步测试用例,当前遇到如下报错:

Cannot read property 'indexOf' of undefined
    at Function.isPendingSpecException

经代码定位,问题疑似由这行mock实现代码导致:

TokenRepositoryMock.findTokenRecordByToken.mockImplementationOnce(
  async () => null,
)

如果把该代码修改为如下形式,报错就会消失:

TokenRepositoryMock.findTokenRecordByToken.mockImplementationOnce(
  async () => ValidToken,
)

但我的实际测试需求是让该方法返回null,以此测试中间件校验失败的分支逻辑。被测的中间件方法代码如下:

public static validate(): Middleware {
  return async (ctx: Context, next: Next): Promise<void> => {
    const token = ctx.data.get('token')

    const tokenRecord: AccountToken | null = await TokenRepository.findTokenRecordByToken(
      token,
    )

    if (!tokenRecord) {
      ctx.status = HttpStatus.UNAUTHORIZED
      throw new InvalidTokenError()
    }

    ctx.data.set('token', tokenRecord)

    await next()
  }
}

之前查阅相关问题时看到部分帖子提到,该报错可能是Intellij IDEA与Jest 24.0.0的兼容问题,但我当前使用的Jest版本为26.6.3,且分别在PhpStorm和命令行环境下运行测试均复现相同错误,请问该如何修复这个问题?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 14:27:04