Ts-jest
lastmod 2023-02-21created 2022-04-0813 edits
Needed when testing TypeScript code in jest.
Installation
Also install @types/jest to get jest type information when writing test units:
A default config file can be generated as follows:
Config
To pass typescript code directly to ts-jest, use preset in the jest property of the package.json file (or in the jest.config.js file) as follows:
Alternatively, matched files can be passed with transform: (needs testing)
module.exports = {
"testMatch": [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)"
],
"transform": {
"^.+\\.(ts|tsx)$": "ts-jest"
},
}
Presets
ts-jest comes with several presets that cover most of a project's basic configuration:
-
ts-jest/presets/defaultorts-jest -
ts-jest/presets/default-esm -
ts-jest/presets/js-with-ts -
ts-jest/presets/js-with-ts-esm -
ts-jest/presets/js-with-babel -
ts-jest/presets/js-with-babel-esm
Isolated Modules option
By default, ts-jest uses the TypeScript compiler in the context of the project, with full type checking and features. But it can also be used to compile each file separately, which TypeScript calls "Isolated Modules". That is exactly what the isolatedModules option (default false) does.
You lose type checking and some features such as const enum, but tests run much faster if you want to use Jest with the cache disabled (jest --no-cache).
Here is how to disable type checking and compile each file as an isolated module.
When applied in jest.config.js:
When applied in package.json:
Troubleshooting
Cannot find module
- Jest Cannot find module error
- [Recommended] Fixing the (Jest) Cannot find module '@src~' from '~' error
Module paths starting with @ need the following setting: