I have a Node project using Typescript and Jest. Currently I have this project structure
With this tsconfig.json
file
"compilerOptions": {
"target": "ES2017",
"module": "commonjs",
"allowJs": true,
"outDir": "dist",
"rootDir": "src",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true
}
this jest.config.js
file
module.exports = {
clearMocks: true,
coverageDirectory: "coverage",
testEnvironment: "node",
};
and this package.json
file
{
"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"
}
}
I created a test file in my tests directory
import { App } from '../src/App';
describe('Generating App', () => {
let app: App;
test('It runs a test', () => {
expect(true).toBe(true);
});
});
but unfortunately I get a syntax error
SyntaxError: C:...\tests\App.test.ts: Unexpected token, expected ";" (5:9)
at my app
variable. It seems the test runner is not able to understand Typescript code. How can I fix my configuration to support Typescript in test files for Jest?
Try to add typescript extension in jest config :
module.exports = {
roots: ['<rootDir>'],
transform: {
'^.+\\.ts?$': 'ts-jest'
},
testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.ts?$',
moduleFileExtensions: ['ts', 'js', 'json', 'node'],
collectCoverage: true,
clearMocks: true,
coverageDirectory: "coverage",
};
And then load the jest config in your package.json test script :
"scripts": {
"test": "jest --config ./jest.config.js",
...
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With