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

Sometimes, we want to fix the “Cannot find name ‘it’” error in Jest TypeScript.

In this article, we’ll look at how to fix the “Cannot find name ‘it’” error in Jest TypeScript.

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

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.

Conclusion

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