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

使用Jest测试NestJS项目时无法编译TypeScript文件求助

解决Jest将TypeScript文件当作JavaScript解析的问题(NestJS项目)

运行npx jest时出现SyntaxError: Missing semicolon错误,本质是Jest没有通过ts-jest转换TypeScript代码,把TypeScript特有的类型注解(比如let appController: PlaceController;)当成JavaScript语法处理,导致报错。以下是针对性的解决思路:

1. 确认依赖安装完整且版本匹配

确保项目已安装ts-jest及相关必需依赖,执行:

npm install --save-dev ts-jest typescript @types/jest

如果之前安装过但问题依旧,可尝试删除node_modules和package-lock.json,重新执行安装命令,避免依赖版本冲突。

2. 明确Jest的转换规则

在jest.config.js中添加transform配置,强制指定.ts/.tsx文件用ts-jest处理,覆盖默认的转换规则:

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['src/**/*.spec.ts'], // 更明确的路径匹配,避免冗余
  verbose: true,
  forceExit: true,
  clearMocks: true,
  resetMocks: true,
  restoreMocks: true,
  bail: false,
  // 新增transform配置,确保TS文件被正确转换
  transform: {
    '^.+\\.(t|j)sx?$': 'ts-jest',
  },
  transformIgnorePatterns: ['<rootDir>/node_modules/'],
};

3. 为测试单独配置tsconfig(可选但推荐)

项目主tsconfig可能包含前端相关配置(比如你的paths里有@app/*等前端路径),可创建测试专用的tsconfig,避免冲突:

  1. 在项目根目录创建tsconfig.test.json:
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2017"
  },
  "include": ["src/server/**/*.spec.ts"] // 仅包含后端测试文件
}
  1. 在jest.config.js中指定该配置:
module.exports = {
  // ...其他配置
  globals: {
    'ts-jest': {
      tsconfig: 'tsconfig.test.json',
    },
  },
};

4. 清除Jest缓存

缓存可能导致旧配置生效,执行以下命令清除缓存后重新运行测试:

npx jest --clearCache
npx jest

5. 检查文件路径与命名

确认所有测试文件的扩展名是.spec.ts,且路径符合testMatch的匹配规则,避免Jest找不到或错误解析文件。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:43:39