使用 Jest 进行测试失败,出现“Unexpected token, expected ";"”错误。

22

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

enter image description here

还有这个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:意外记号,期望“;”(第5行,第9个字符)

出现在我的app变量处。看起来测试运行程序无法理解Typescript代码。我应该如何修复配置以支持Jest中的测试文件中的Typescript?

3个回答

31

尝试在jest配置中添加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 目录.. =? - user9945420
我觉得问题出在你把测试文件放在 src 文件夹之外,所以我更新了 jest 配置,将 roots: ['<rootDir>/src'], 替换为 roots: ['<rootDir>'], 现在应该可以正常工作了 :) - Putxe
你的测试位于 tests 文件夹中,但在 jest.config.js 中你指定了文件夹 __tests__。路径不同,因此找不到匹配项。 - al-bulat
2
在我的情况下,它没有将 ts 文件转译为 js。当我添加了答案的 transform 属性后,它开始转译并通过了另一个问题,该问题通过 tsConfig 属性得到解决。谢谢! - uzay95
1
npm install ts-node -D 并将 transform: { '^.+\\.ts?$': 'ts-jest' } 添加到 Jest 配置中,解决了我的问题,感谢 @Putxe. - Zymotik

1
在我的情况下,失败是因为我没有正确设置Jest的typescript支持。我通过安装以下预设并将babel配置文件设置如下来解决了这个问题:

babel.config.json

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-typescript",
    ["@babel/preset-react", { "runtime": "automatic" }]
  ]
}

0

tsconfig.json

"compilerOptions": {
  "jsx": "react-jsx"
},

1
你的回答可以通过提供更多支持信息来改进。请[编辑]以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Tyler2P
这实际上对我来说是解决方案,所以谢谢。 - Jeremy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接