安装jest时出现“describe未定义”的错误

104

我在项目中安装了jest v24.7.1


npm install jest -D

然后我开始编写一些测试文件,但是我遇到了以下eslint错误:


'describe' is not defined. eslint (no-undef)
'it' is not defined. eslint (no-undef)
'expect' is not defined. eslint (no-undef)

eslintrc.js:

module.exports = {


env: {
    browser: true,
    es6: true
  },
  extends: ["airbnb", "prettier", "prettier/react"],
  globals: {
    Atomics: "readonly",
    SharedArrayBuffer: "readonly"
  },
  parserOptions: {
    ecmaFeatures: {
      jsx: true
    },
    ecmaVersion: 2018,
    sourceType: "module"
  },
  plugins: ["react"],
  rules: {}
};

我该添加另一个规则还是插件来解决这个问题?

4个回答

268
.eslintrc.js文件中添加以下行。
"env": {
    "jest": true
}
或者
{
  "plugins": ["jest"]
},
"env": {
  "jest/globals": true
}

了解更多详情请查看此处,它也定义相同内容。

希望您已安装eslint-plugin-jest包。如果没有,请参阅文档

配置ESLint的所有详细信息。


如果您正在使用VS Code,可能需要通过按下Ctrl / Command + Shift + P来重新启动Es-lint服务器,然后在命令解释器中搜索“Restart Eslint”并单击以继续Eslint服务器。 - Mwibutsa Floribert
想要补充一下,jest 也使用了一些 jasmine 的定义,比如 fail,因此可能需要添加 jasmine: true - rcbevans

5
在文件的头部添加以下注释行。
/* globals describe, expect, it */ 

1

对于jest 27,所有这些都不应该是必要的。
删除node_modulespackage-lock.json
然后运行npm i


谢谢!这就是对我有效的方法... - shanti

-4
在你的测试文件顶部添加/* eslint-disable no-undef */

sample.test.js

/* eslint-disable no-undef */
function sum(a, b) {
  return a + b;
}

describe("adds 1 + 2 to equal 3", () => {
  expect(sum(1, 2)).toBe(3);
});


这是不正确的 - 你不应该仅仅隐藏错误,将jest添加到eslint环境中对我有所帮助。 - Shannon Hochkins

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接