Skip to content
Search

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:

yarn add -D ts-jest @types/jest

A default config file can be generated as follows:

yarn ts-jest config:init

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:

  "jest": {
    "preset": "ts-jest"
  }

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/default or ts-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:

module.exports = {
  // [...]
  globals: {
    'ts-jest': {
      isolatedModules: true
    }
  }
};

When applied in package.json:

{
  // [...]
  "jest": {
    "globals": {
      "ts-jest": {
        "isolatedModules": false
      }
    }
  }
}

Troubleshooting

Cannot find module

Module paths starting with @ need the following setting:

  "jest": {
    "preset": "ts-jest",
    "moduleNameMapper": {
      "@/(.*)$": "<rootDir>/src/$1"
    }
  }

See also

Favorite site

author Zer0 sitemap