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

Jest测试本地通过但Bitbucket流水线中失败问题排查

问题描述

我编写了如下自定义异常类代码:

export class UnprocessableException extends Error {
    constructor(message: string) {
        super(responseStatus.UNPROCESSABLE, message);
    }
}

并通过Jest编写测试用例验证:

try {
    ....
} catch (e) {
    expect(e).toBeInstanceOf(UnprocessableException);
}

该测试在本地执行可通过,但使用相同命令在Bitbucket流水线中运行时失败,报错信息为:

Expected: UnprocessableException 

Received: Error

请问为何Jest与Bitbucket会出现此类类型不兼容问题?

问题原因及解决办法

这并非Jest与Bitbucket的类型不兼容问题,核心在于自定义Error类的原型链未正确配置,导致不同环境下(本地与CI环境的TypeScript编译配置可能存在差异),instanceof判断失效。

核心原因

继承原生Error类时,TypeScript默认编译输出可能无法正确设置原型链。在部分环境(比如CI环境的编译目标或配置更严格)中,UnprocessableException的实例会被识别为原生Error,而非自定义异常类的实例。

修复方案

修改自定义异常类,手动修正原型链:

export class UnprocessableException extends Error {
    constructor(message: string) {
        super(responseStatus.UNPROCESSABLE, message);
        // 修正原型链,确保instanceof判断生效
        Object.setPrototypeOf(this, UnprocessableException.prototype);
        // 可选:设置name属性,提升调试便利性
        this.name = 'UnprocessableException';
    }
}

额外检查项:

  • 确保本地与Bitbucket流水线使用的TypeScript版本、tsconfig.json配置完全一致,比如target、lib等编译选项,避免因编译输出差异引发问题。
  • 若项目使用Babel,需确认Babel配置正确处理类继承,比如启用@babel/plugin-transform-classes插件,或采用符合ES6+标准的编译配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 00:12:40