59

I try to create an intial setup for Jest in React + TypeScript. I have completed the initial setup and try to check whether the test runs. When I run the test using the command npm test, I am getting the following error:

Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i @types/jest` or `npm i @types/mocha`.

I have installed the types for Jest as well as removed the types in tsconfig.json, but still I am getting the same error.

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "plugins": [{ "name": "typescript-tslint-plugin" }],
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "pretty": true,
    "baseUrl": "src",
    "types": ["jest"],
    "typeRoots": ["./src/types"],
    "suppressImplicitAnyIndexErrors": true
  },
  "include": ["src", "node_modules/@types/jest"],
  "exclude": ["node_modules"]
}
`

Package.json


    "jest": {
        "transform": {
          ".(ts|tsx)": "ts-jest"
        },
        "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js)$",
        "moduleFileExtensions": [
          "ts",
          "tsx",
          "js"
        ]
      },
      "devDependencies": {
        "@babel/plugin-proposal-export-default-from": "^7.2.0",
        "@types/enzyme": "^3.9.3",
        "@types/jest": "^24.0.14",
        "enzyme": "^3.10.0",
        "gh-pages": "^1.2.0",
        "husky": "^2.2.0",
        "jest": "^24.8.0",
        "node-sass": "^4.11.0",
        "prettier": "^1.17.0",
        "react-scripts": "2.1.8",
        "react-test-renderer": "^16.8.6",
        "stylelint": "^9.3.0",
        "stylelint-config-recommended-scss": "^3.2.0",
        "stylelint-config-standard": "^18.2.0",
        "stylelint-order": "^0.8.1",
        "stylelint-scss": "^3.1.3",
        "ts-jest": "^24.0.2",
        "tslint": "^5.16.0",
        "tslint-config-prettier": "^1.18.0",
        "tslint-plugin-prettier": "^2.0.1",
        "tslint-react": "^4.0.0",
        "tslint-react-hooks": "^2.1.0"
      }

JKD
  • 1,279
  • 1
  • 6
  • 26
Nidhin Kumar
  • 3,278
  • 9
  • 40
  • 72

12 Answers12

94

Install

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

jest.config.js -- at root

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

tsconfig.json

{
    "compilerOptions": {
     ...

      "types": ["reflect-metadata", "jest"],
      "typeRoots": ["./types", "./node_modules/@types"]
     
     ...
    },
    "exclude": ["node_modules", "**/*.spec.ts", "**/*.test.ts"],
    "include": ["./src/**/*.tsx", "./src/**/*.ts"]
  }
Tamlyn
  • 22,122
  • 12
  • 111
  • 127
Shailesh Jha
  • 1,122
  • 1
  • 8
  • 9
  • I had `@types/jest, `"types": ["jest"], and `"typeRoots": ["./types"]` in the tsconfig and wasn't working. I only changed `typeRoots` to be `"typeRoots": ["./types", "./node_modules/@types"]` and it worked with no other changes – gabe May 03 '23 at 22:02
28

Import this in any of your test files:

import '@types/jest';
Yogesh Devgun
  • 1,297
  • 1
  • 19
  • 36
25

For me, the problem was that my tsconfig.json was built with

  "include": [
    "src"
  ]

I had to change that to

  "include": [
    "src",
    "tests"
  ]

(My tests all being in directory 'tests')

HJo
  • 1,902
  • 1
  • 19
  • 30
  • 11
    This will include tests folder in the output directory which is not ideal – schystz Apr 10 '20 at 08:07
  • 1
    @schystz I agree that this is not ideal but so far it's been the only way to get my tests not to make eslint go crazy. I also tried moving my __tests__ folder into my src folder, hoping that somehow inheritance would allow the jest types to be found but the exclude would keep it from being in the output. Alas, no. If anyone else has any advice, I'd take it. – Adam Tuttle Jan 12 '22 at 21:29
  • You can add a "child" config for tests: ./test/tsconfig.json `{ "extends": "../tsconfig.json", "include": ["../src/**/*", "**/*"] }` like https://github.com/cloudflare/miniflare-typescript-esbuild-jest/blob/master/test/tsconfig.json – ptim Jul 25 '22 at 07:19
  • Didn't see this answer below, which answers your question @H Johnson https://stackoverflow.com/a/66773251/2586761 – ptim Jul 25 '22 at 07:46
24

In tsconfig.json add the below code

"types": ["jest"],
"typeRoots": ["./src/types", "node_modules/@types"],
Nidhin Kumar
  • 3,278
  • 9
  • 40
  • 72
21

I had to add "@types/jest" to my "types" array in my tsconfig.json.

jeti
  • 1,650
  • 1
  • 19
  • 28
13

I've tried all the above solutions, but unfortunately, none of them worked out for me. The solution that worked in my case though was to reference the type definitions via /// <reference types="@types/jest" />; at the top of the file. You need to install @types/jest package first. The downside to it is that you have to import it into all the files.

Devorein
  • 1,112
  • 2
  • 15
  • 23
  • 1
    Tried everything else; this was it for me. – Charles Chen Mar 04 '22 at 14:28
  • 1
    God I hate Jest and its inconceivable configuration soup. Nothing else worked except this. Okay. Glad I can move on to actually productive things. – TeemuK May 18 '22 at 10:13
  • For me, installing @types/jest and then adding '@types/jest' to 'types' in my tsconfig.json meant I didn't need to add it to every file – paddyfields Nov 28 '22 at 12:07
6

Install @types/jest npm install @types/jest and add config for jest:

// package.json
// ...
"jest": {
  "globals": {
    "ts-jest": {
      "tsconfig": "path_to_our_tests/jest.tsconfig.json"
    }
  }
}

Create jest.tsconfig.json in your test directory and adjust like this:

// path_to_our_tests/jest.tsconfig.json"
{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "types": ["jest"]
  },
  "include": ["../src", "**/*"]
}

Ensure that your root tsconfig only includes src files, not test files:

// tsconfig.json
{
  // ...
  "include": ["src"]
}

This way you don't change the global configs of your project, and prevents breaking your code.

Both configs should pass a compiler check:

npx tsc && npx tsc -p path_to_our_tests/jest.tsconfig.json

ptim
  • 14,902
  • 10
  • 83
  • 103
vandersondf
  • 839
  • 1
  • 9
  • 8
  • In my case, my root tsconfig had no "include" field, so it was checking my tests/* directory as well... adding `"include": "src"` completed the setup for me – ptim Jul 25 '22 at 07:34
  • 1
    Updated your answer to add detail around `include` and compiler checking - hope you don't mind! Inspired by https://github.com/cloudflare/miniflare-typescript-esbuild-jest/blob/master/test/tsconfig.json – ptim Jul 25 '22 at 07:49
  • This is absolutely the most complete and easiest answer! – derek Nov 06 '22 at 03:57
1

Updating ts-loader to v6.0.1 or above can do a trick.

0

I had to install jest in the devDependency:

npm i --save-dev @types/jest
Arefe
  • 11,321
  • 18
  • 114
  • 168
0

None of the above solutions worked for me. Not even importing '@types/jest' which was throwing error while doing npm test to import 'jest' instead. The only solution for me is import { describe, it, beforeEach } from '@jest/globals' to test files

0

After inspecting the output of npx ts-jest config:init (as suggested in the ts-jest documentation) I discovered that adding this line to the top of my jest.config.js file did the trick:

/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
John J. Camilleri
  • 4,171
  • 5
  • 31
  • 41
-1

In my case, the problem was that I actually didn't have a jest folder in my ./node_modules/@types directory. Running npm i @types/jest claimed that the package was up to date but it still didn't exist in my node_modules/@types where it should be installed so the error persisted.

I fixed the issue by installing @types/jest globally and copying the installed package to my ./node_modules/@types.

To install @jest/types globally run:

npm i -g @types/jest

To get the path to your global node_modules run:

npm root -g

To confirm that the @types/jest package is there run:

ls $(npm root -g)/@types

Then cd into your project directory and run

cp -R $(npm root -g)/@types/jest ./node_modules/@types

to copy it to your local node_modules.

Dharman
  • 30,962
  • 25
  • 85
  • 135
martinkaburu
  • 487
  • 6
  • 18