我有一个使用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:意外令牌,预期为“;” (5:9)
在我的app
变量中。似乎测试运行程序无法理解Typescript代码。如何修复我的配置以支持Jest测试文件中的Typescript?
答案 0 :(得分:4)
尝试在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",
};
然后将jest配置加载到package.json测试脚本中:
"scripts": {
"test": "jest --config ./jest.config.js",
...
},