Sometimes, we want to fix the “Cannot find name ‘it’” error in Jest and TypeScript.
In this article, we’ll look at how to fix the “Cannot find name ‘it’” error in Jest and TypeScript.
How to fix the “Cannot find name ‘it’” error in Jest and TypeScript?
To fix the “Cannot find name ‘it’” error in Jest and TypeScript, we add the ts-jest
transform to our test files by adding the entry in jest.config.js
.
We install ts-jest
by running
npm install jest @types/jest ts-jest
For instance, we write
module.exports = {
roots: ["<rootDir>/src"],
transform: {
"^.+\.tsx?$": "ts-jest",
},
testRegex: "(/__tests__/.*|(\.|/)(test|spec))\.tsx?$",
moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
};
in jest.config.ts
to transform "^.+\.tsx?$"
files with ts-jest
.
Then in tsconfig.json
, we add
{
"compilerOptions": {
//...
"types": ["reflect-metadata", "jest"],
"typeRoots": ["./types", "./node_modules/@types"]
//...
},
"exclude": ["node_modules", "**/*.spec.ts", "**/*.test.ts"],
"include": ["./src/**/*.tsx", "./src/**/*.ts"]
}
to add the 'jest'
type to the types
option.
Now the TypeScript compiler should be aware of Jest types.
Conclusion
To fix the “Cannot find name ‘it’” error in Jest and TypeScript, we add the ts-jest
transform to our test files by adding the entry in jest.config.js
.