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

@swc/jest设target为es2021仍生成非类代码,Jest测试报错求助

解决Jest+SWC编译NestJS自定义异常过滤器时的"Class constructor cannot be invoked without 'new'"错误

问题背景

使用NestJS编写继承自@nestjs/core中BaseExceptionFilter的自定义异常过滤器:

import { BaseExceptionFilter } from "@nestjs/core";
export class AllExceptionsFilter extends BaseExceptionFilter {
   // 自定义实现逻辑
}

Jest配置文件jest.config.js如下:

module.exports = {
  testEnvironment: "jsdom",
  testMatch: ["**/*.spec.ts", "**/*.spec.js"],
  testPathIgnorePatterns: ["/test/"],
  // UUID uses esmodules so we need to convert it to commonjs
  transformIgnorePatterns: ["/node_modules/(?!uuid)"],
  transform: {
    '^.+\\.(t|j)sx?$': ['@swc/jest', {
      jsc: {
        target: "es2021",
      },
    }],
  }
};

运行测试时触发错误:

TypeError: Class constructor BaseExceptionFilter cannot be invoked without 'new'

      30 |     __extends(AllExceptionsFilter, _super);
      31 |     function AllExceptionsFilter() {
    > 32 |         return _super !== null && _super.apply(this, arguments) || this;
         |                                          ^
      33 |     }
      34 |     AllExceptionsFilter.prototype["catch"] = function (exception, host) {
      35 |         var httpAdapter = this.httpAdapterHost.httpAdapter;

报错原因

@nestjs/core提供的BaseExceptionFilter是ES原生类,而当前SWC配置下,自定义过滤器被编译成了ES5兼容的伪类(通过__extends和函数模拟实现),这种伪类用_super.apply(this, arguments)调用父类构造函数,不符合原生类必须用new关键字调用构造函数的规则,因此触发错误。即使设置了target: es2021,如果缺少禁用松散模式、正确配置装饰器解析等关键配置,SWC仍会降级编译类语法。

解决方案

1. 调整SWC编译配置

修改jest.config.js中的SWC配置,确保输出原生ES2021类语法,并适配NestJS的装饰器需求:

module.exports = {
  testEnvironment: "jsdom",
  testMatch: ["**/*.spec.ts", "**/*.spec.js"],
  testPathIgnorePatterns: ["/test/"],
  // 若@nestjs/core为ES模块,需加入transformIgnorePatterns白名单
  transformIgnorePatterns: ["/node_modules/(?!uuid|@nestjs)"],
  transform: {
    '^.+\\.(t|j)sx?$': ['@swc/jest', {
      module: {
        type: "commonjs", // 适配Jest的CommonJS运行环境
      },
      jsc: {
        target: "es2021",
        parser: {
          syntax: "typescript",
          decorators: true, // 启用TypeScript装饰器解析
        },
        transform: {
          legacyDecorator: true, // 兼容NestJS的装饰器语法
          decoratorMetadata: true, // 启用装饰器元数据支持
        },
        loose: false, // 禁用松散模式,强制输出原生类语法
      },
    }],
  }
};

2. 同步tsconfig.json配置

确保项目根目录的tsconfig.json启用对应编译选项,让SWC读取一致的规则:

{
  "compilerOptions": {
    "target": "ES2021",
    "module": "CommonJS",
    "strict": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "skipLibCheck": true
  }
}

3. 更新SWC依赖

如果上述配置无效,尝试更新@swc/jest和@swc/core到最新版本,旧版本可能存在编译目标解析的bug:

npm update @swc/jest @swc/core

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:55:00