How to Prevent TypeScript Type-Checking in Jest Tests?

If you wish to prevent TypeScript from type-checking your Jest tests, you can do either of the following:

  1. Use babel-jest as a Transformer;
  2. Use ts-jest as a Transform With isolatedModules.

#Using babel-jest as a Transformer

If you use babel-jest as a transformer to transpile TypeScript code into JavaScript, by default, it won't type-check your tests as they are run.

You can set it up in the following steps:

  1. Install Relevant Packages

    npm install --save-dev babel-jest @babel/core @babel/preset-typescript @babel/preset-env
    
  2. Specify Presets in Babel Configuration

    // babel.config.js
    module.exports = {
      presets: [
        ['@babel/preset-env', { targets: { node: 'current' } }],
        '@babel/preset-typescript',
      ],
    };
    
  3. Set babel-jest as Transformer in Jest Configuration

    // jest.config.js
    module.exports = {
      // ...
      transform: {
        '^.+\\.tsx?$': 'babel-jest',
      },
      // ...
    }
    

#Using ts-jest as a Transform With isolatedModules

If you use ts-jest as a transformer to transpile TypeScript code into JavaScript, you can set it up in the following way to prevent it from type-checking tests:

  1. Install Relevant Packages

    npm install --save-dev ts-jest @types/jest
    
  2. Set ts-jest as Transformer in Jest Configuration

    // jest.config.js
    module.exports = {
      // ...
      transform: {
        '^.+\\.tsx?$': [ 'ts-jest', { isolatedModules: true } ],
      },
      // ...
    }
    

    Setting the isolatedModules option to true prevents type-checking when tests are run.

By default, ts-jest will type-check your Jest tests.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.