【问题标题】:Jest test fails with Unexpected token, expected ";"Jest 测试失败,出现 Unexpected token,expected ";"
【发布时间】:2020-01-15 04:13:25
【问题描述】:

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

有了这个tsconfig.json 文件

  "compilerOptions": {
    "target": "ES2017",
    "module": "commonjs",
    "allowJs": true,
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true
  }

这个jest.config.js 文件

module.exports = {
  clearMocks: true,
  coverageDirectory: "coverage",
  testEnvironment: "node",
};

还有这个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"
  }
}

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

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

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

  test('It runs a test', () => {
    expect(true).toBe(true);
  });
});

但不幸的是我遇到了语法错误

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

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

【问题讨论】:

    标签: javascript node.js typescript jestjs


    【解决方案1】:

    尝试在 jest config 中添加 typescript 扩展:

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

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

    "scripts": {
        "test": "jest --config ./jest.config.js",
        ...
      },
    

    【讨论】:

    • 感谢您的帮助。当我运行npm run test 时,模式返回0 匹配Run with '--passWithNoTests' to exit with code 0 In C:\... 6 files checked,似乎无法使用tests 目录.. =?
    • 我认为这是因为您的测试在 src 文件夹之外,所以我通过添加 roots: ['&lt;rootDir&gt;'], 而不是 roots: ['&lt;rootDir&gt;/src'], 更新了 jest 配置,它现在应该可以工作了 :)
    • 您的测试位于tests 文件夹中,但在jest.config.js 中您已指定文件夹__tests__。指定了不同的路径,但没有匹配的。
    • 在我的情况下,它不会将 ts 文件转换为 js。当我添加答案的转换属性时,它开始转换并传递给另一个由 tsConfig 属性解决的问题。谢谢!
    • npm install ts-node -D 并将transform: { '^.+\\.ts?$': 'ts-jest' } 添加到开玩笑的配置中解决了我的问题,谢谢@Putxe
    猜你喜欢
    • 2022-06-16
    • 2020-12-28
    • 2018-03-29
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 2019-09-11
    • 2019-11-10
    • 1970-01-01
    相关资源
    最近更新 更多