Jest 测试失败,出现意外令牌,预期为“;”

hrp*_*xQ4 16 javascript node.js typescript jestjs

我有一个使用 Typescript 和 Jest 的 Node 项目。目前我有这个项目结构

在此处输入图片说明

有了这个tsconfig.json文件

  "compilerOptions": {
    "target": "ES2017",
    "module": "commonjs",
    "allowJs": true,
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true
  }
Run Code Online (Sandbox Code Playgroud)

这个jest.config.js文件

module.exports = {
  clearMocks: true,
  coverageDirectory: "coverage",
  testEnvironment: "node",
};
Run Code Online (Sandbox Code Playgroud)

和这个package.json文件

{
  "scripts": {
    "start": "node dist/App.js",
    "dev": "nodemon src/App.ts",
    "build": "tsc -p .",
    "test": "jest"
  },
  "dependencies": {
    "commander": "^3.0.1"
  },
  "devDependencies": {
    "@types/jest": "^24.0.18",
    "@types/node": "^12.7.4",
    "jest": "^24.9.0",
    "nodemon": "^1.19.2",
    "ts-jest": "^24.0.2",
    "ts-node": "^8.3.0",
    "typescript": "^3.6.2"
  }
}
Run Code Online (Sandbox Code Playgroud)

我在我的测试目录中创建了一个测试文件

import { App } from '../src/App';

describe('Generating App', () => {
  let app: App;

  test('It runs a test', () => {
    expect(true).toBe(true);
  });
});
Run Code Online (Sandbox Code Playgroud)

但不幸的是我收到一个语法错误

SyntaxError: C:...\tests\App.test.ts: Unexpected token, expected ";" (5:9)

在我的app变量。测试运行器似乎无法理解 Typescript 代码。如何修复我的配置以在 Jest 的测试文件中支持 Typescript?

Put*_*txe 20

尝试在 jest 配置中添加打字稿扩展名:

module.exports = {
  roots: ['<rootDir>'],
  transform: {
    '^.+\\.ts?$': 'ts-jest'
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.ts?$',
  moduleFileExtensions: ['ts', 'js', 'json', 'node'],
  collectCoverage: true,
  clearMocks: true,
  coverageDirectory: "coverage",
};
Run Code Online (Sandbox Code Playgroud)

然后在 package.json 测试脚本中加载 jest 配置:

"scripts": {
    "test": "jest --config ./jest.config.js",
    ...
  },
Run Code Online (Sandbox Code Playgroud)

  • 就我而言,它不会将 ts 文件转换为 js。当我添加答案的转换属性时,它开始转换并传递给另一个由 tsConfig 属性解决的问题。谢谢! (2认同)