Configure Jest global tests setup with .ts file (TypeScript)
For anyone with TS error with @remeus's answer, the following change will do the trick:
require('ts-node').register({
transpileOnly: true,
});
If you're using absolute imports, use this:
require('tsconfig-paths').register();
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": {
"tsconfig": "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.
Global setup is performed before a ts environment is made available, so a workaround is to create the environment manually by requiring ts-node at the beginning of the file.
In your jest configuration (package.json
or jest.config.js
):
"globalSetup": "./globalSetup.ts"
Then in globalSetup.ts
:
require('ts-node/register');
const setup = (): void => {
// whatever you need to setup globally
};
export default setup;
You can read more about ts-node on github.