You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

已安装Mocha类型并配置tsconfig仍报错:Cannot find name 'it'

Node.js+TypeScript项目运行Mocha测试时出现类型错误

错误信息

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.

我已经按提示完成了以下操作,但错误仍未解决:

  • 安装了@types/mocha开发依赖
  • 在tsconfig.json的compilerOptions.types中添加了mocha
  • 在测试命令的TS_NODE_COMPILER_OPTIONS环境变量里也配置了types: ["mocha"]

项目配置文件

package.json(包含测试脚本)

{
  "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"
    ]
  }
}

内容的提问来源于stack exchange,提问作者chrispytoes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 20:00:05