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

ESLint无法识别Jest全局变量问题求助

ESLint无法识别Jest全局方法(describe/it等)的问题解决

环境信息

  • ESLint版本:8.21.0
  • Jest版本:27.0.6
  • 相关依赖包:
"eslint": "^8.21.0",
"eslint-config-semistandard": "^17.0.0",
"eslint-config-standard": "^17.0.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-jest": "^26.7.0",
"eslint-plugin-n": "^15.2.4",
"eslint-plugin-promise": "^6.0.0"

问题现象

ESLint本身运行正常,但describe、it等Jest全局方法被标记为未定义错误。此前使用Airbnb相关插件配置时无此问题,当前ESLint配置如下:

{
  "extends": [
    "eslint:recommended",
    "semistandard",
    "plugin:jest/recommended"
  ],
  "env": {
    "es6": true,
    "jest/globals": true,
    "mocha": true
  },
  "globals": {
    "Atomics": "readonly",
    "SharedArrayBuffer": "readonly"
  },
  "parserOptions": {
    "ecmaVersion": 2020
  },
  "plugins": ["jest"],
  "rules": {
    "n/no-path-concat": "off",
    "no-console": "warn",
    "jest/no-disabled-tests": "warn",
    "jest/no-focused-tests": "error",
    "jest/no-identical-title": "error"
  }
}

已尝试的无效操作

  • 在env中添加"plugins": ["jest"]和"jest/globals": true
  • 仅配置"extends": ["plugin:jest/recommended"]

解决方案

核心问题

你同时启用了mocha环境和jest环境,两者的全局变量定义冲突,导致ESLint无法正确识别Jest的全局方法。此外,plugin:jest/recommended已经内置了jest/globals的配置,无需在env中重复声明。

修改后的配置

{
  "extends": [
    "eslint:recommended",
    "semistandard",
    "plugin:jest/recommended"
  ],
  "env": {
    "es6": true
    // 移除mocha环境,消除与jest的全局变量冲突
  },
  "globals": {
    "Atomics": "readonly",
    "SharedArrayBuffer": "readonly"
  },
  "parserOptions": {
    "ecmaVersion": 2020
  },
  "plugins": ["jest"],
  "rules": {
    "n/no-path-concat": "off",
    "no-console": "warn",
    "jest/no-disabled-tests": "warn",
    "jest/no-focused-tests": "error",
    "jest/no-identical-title": "error"
  }
}

额外注意事项

如果你的测试文件命名不符合默认规则(比如不是.test.js或.spec.js结尾),需要在配置中添加settings指定测试文件匹配模式:

"settings": {
  "jest": {
    "testMatch": ["**/__tests__/**/*.js", "**/?(*.)+(spec|test).js"]
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:43:04