Jest and TypeScript

Learn how to use Jest for testing TypeScript applications.

TypeScript configuration options

Jest is fully compatible with TypeScript applications, but there are a couple of nuances to this environment. We have two options for configuring Jest with TypeScript: babel and ts-jest. Unless an application is already using a babel configuration in its testing environment, we think that ts-jest is the more straightforward path.

ts-jest

This package, available on our preferred package registry, is a TypeScript processor for Jest. All we need to do is start writing our test files as .test.ts instead of .test.js and change some things in our Jest configuration. First, we inform Jest that we will be using .ts (and any other TypeScript extensions we need, such as .tsx) for our modules. We can update the moduleFileExtensions field to reflect this:

{
  moduleFileExtensions: ['js', 'ts']
}

In addition, any other configurations that point to JavaScript files through paths or regex also need to account for the presence of TypeScript files. Therefore, let’s say we have the following code snippet:

{
  collectCoverageFrom: ['src/*.(js | jsx)']
}

We need to change this to the following:

{
  collectCoverageFrom: ['src/*.(js | jsx | ts | tsx)']
}

We also need to tell Jest to use ts-jest to process our TypeScript files. To do this, we add a key-value pair to the transform field whose key represents all TypeScript file extensions it can expect, and whose value is the package name:

{
  transform: {
    '\\.(ts | tsx)$': 'ts-jest'
  }
}

babel-jest

If we’re already using a babel configuration inside our codebase (or want to), we can use this to enable TypeScript support.

Babel configuration for Jest requires several packages:

  • babel-jest
  • @babel/core
  • @babel/preset-env

These can be installed using yarn add --dev babel-jest @babel/core @babel/preset-env.

Once these are installed, the app will need to have babel configured either through the package.json file or a separate babel.config.js file:

Get hands-on with 1200+ tech skills courses.