Search code examples
typescriptmocha.jsts-node

"Cannot find name 'it'" but Mocha types are installed and added to compilerOptions


I'm getting this error trying to run Mocha tests in a node.js + typescript app:

Cannot find name 'it'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add 'jest' or 'mocha' to the types field in your tsconfig.

I did exactly what it says, installed @types/mocha and added mocha to compilerOptions.types in both the project tsconfig.json, and the TS_NODE_COMPILER_OPTIONS variable, but the error still shows.

This is my package.json, which includes my test command:

{
  "name": "vwan-compiler",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "set TS_NODE_COMPILER_OPTIONS={\"module\":\"commonjs\",\"typeRoots\":[\"./src/types/*.d.ts\"],\"types\":[\"mocha\"]} && mocha -r ts-node/register 'src/**/*.test.ts'"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/chai": "^4.3.14",
    "@types/express": "^4.17.21",
    "@types/jsonwebtoken": "^9.0.6",
    "@types/mocha": "^10.0.6",
    "@types/node": "^20.11.30",
    "@types/pg-pool": "^2.0.6",
    "@types/supertest": "^6.0.2",
    "chai": "^5.1.0",
    "dotenv": "^16.4.5",
    "jest": "^29.7.0",
    "mocha": "^10.4.0",
    "supertest": "^6.3.4",
    "ts-node": "^10.9.2",
    "typescript": "^5.4.3"
  },
  "dependencies": {
    "express": "^4.19.2",
    "jsonwebtoken": "^9.0.2",
    "knex": "^3.1.0",
    "pg-pool": "^3.6.1"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "types": [
      "node",
      "mocha"
    ],
    "typeRoots": [
      "./node_modules/@types",
      "./src/types/*.d.ts"
    ]
  },
}

Solution

  • You forgot to add ./node_modules/@types to typeRoots

    If typeRoots is specified, only packages under typeRoots will be included

    But we need to add node_modules/@types so that TSC can look for the type definitions for packages.

    "scripts": {
      "test": "set TS_NODE_COMPILER_OPTIONS={\"module\":\"commonjs\",\"typeRoots\":[\"./src/types\", \"./node_modules/@types\"],\"types\":[\"mocha\"]} && mocha -r ts-node/register '**/*.test.ts'"
    },
    

    See this anwser to know the usage of typeRoots and types

    The difference between typeRoots and types:

    types differs from typeRoots in that it is about specifying only the exact types you want included, whereas typeRoots supports saying you want particular folders.

    Besides, you just need to specify the folder path of the types like ./src/types rather than ./src/types/*.d.ts