Configure Jest Global Tests Setup With .ts File (TypeScript)
Answer :
I found a solution.
My initial project structure was:
.
|--src
| |--service.ts
|--tests
| |--service.test.ts
|--dist
|--tsconfig.json
|--package.json
Jest configuration in package.json:
"jest": {
"globals": {
"ts-jest": {
"tsConfigFile": "tsconfig.json"
}
},
"moduleFileExtensions": ["ts","js"],
"transform": {
"^.+\\.(ts|tsx)$": "./node_modules/ts-jest/preprocessor.js"
},
"testMatch": [
"**/tests/**/*.test.(ts|js)"
],
"testEnvironment": "node"
}
With this configuration ts-jest
perform in memory transpiling of the .ts files.
I have outDir
option in compilerOptions
of my tsconfig.json
, but nothing is written in that outDir and because I cann't use transpiled jest-config.js
Then I move tests folder in src and change Jest config.
New structure of the project is:
.
|--src
| |--service.ts
| |--tests
| |--service.test.ts
| |--jest-config.ts
|--dist
|--tsconfig.json
|--package.json
New Jest config is:
"jest": {
"globalSetup": "./dist/tests/jest-config.js",
"moduleFileExtensions": ["ts", "js", "json"],
"testMatch": [
"**/dist/**/*.test.js"
],
"testEnvironment": "node"
}
Now I can use jest-config.js for global setup in Jest.
Addition
Jest setup file (in my example jest-config.js) must export one async function:
module.exports = async function() { ... }
Before running the tests, you need to compile source .ts files.
Comments
Post a Comment