Categories
JavaScript Answers TypeScript Answers

How to fix the “Cannot find name ‘it'” error in Jest TypeScript?

Spread the love

To fix the "Cannot find name ‘it’" error in Jest TypeScript, we need to install a few packages and change the test config.

First, we install the Jest TypeScript packages with

npm i npm install jest @types/jest ts-jest

Then in the jest.config.js file at the root folder, we add

module.exports = {
  roots: ['<rootDir>/src'],
  transform: {
    '^.+\\.tsx?$': 'ts-jest',
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
}

so Jest can pick up test files and module files in the tests.

Then in tsconfig.json, we have

{
  "compilerOptions": {
    //...
    "types": ["reflect-metadata", "jest"],
    "typeRoots": ["./types", "./node_modules/@types"]
    //...
  },
  "exclude": ["node_modules", "**/*.spec.ts", "**/*.test.ts"],
  "include": ["./src/**/*.tsx", "./src/**/*.ts"]
}

so that the TypeScript compiler can pick up the TypeScript source code files in the folder by putting the include array.

And we exclude paths of non production source files with the exclude option.

We add 'jest' to types so that the type definitions of Jest is picked up by the TypeScript compiler.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *