[英]eslint throws `no-undef` errors when linting Jest test files
我正在使用 Jest 来编写一些规范,并使用 ESLint 来检查样式。
对于我的foo.spec.js
测试,eslint 不断抛出以下错误。 似乎认为jest
, beforeEach
, afterEach
等......未在该文件中定义。
11:1 error 'beforeEach' is not defined no-undef
12:3 error 'jest' is not defined no-undef
14:13 error 'jest' is not defined no-undef
18:1 error 'afterEach' is not defined no-undef
20:1 error 'describe' is not defined no-undef
21:3 error 'it' is not defined no-undef
25:5 error 'expect' is not defined no-undef
28:5 error 'expect' is not defined no-undef
31:5 error 'expect' is not defined no-undef
34:3 error 'it' is not defined no-undef
38:5 error 'expect' is not defined no-undef
41:5 error 'jest' is not defined no-undef
42:5 error 'expect' is not defined no-undef
43:5 error 'expect' is not defined no-undef
46:3 error 'it' is not defined no-undef
54:5 error 'expect' is not defined no-undef
58:5 error 'jest' is not defined no-undef
我相信这些是由 jest 自动包含的,因此不需要在我的规范文件中明确导入。 事实上,我通过我的jest.setup.js
文件导入的唯一东西是
import "react-testing-library/cleanup-after-each";
import "jest-dom/extend-expect";
有没有一种方法可以消除这些错误,而不必在每个单独文件或内联文件的顶部禁用 eslint 规则?
谢谢!
请将以下内容添加到您的 .eslintrc 文件中:
{
"overrides": [
{
"files": [
"**/*.spec.js",
"**/*.spec.jsx"
],
"env": {
"jest": true
}
}
]
}
您无需添加此覆盖选项并指定jest
应该在哪些文件中可用。 仅添加env
字段就足够了。
.eslintrc.js :
module.exports = {
env: {
jest: true
},
//...
}
有一个类似的问题,eslint 为我的 jest setup.js 文件抛出 no-undef 错误,其中包含一些 jest.mocks。
最终通过使用ESLint 插件来修复它 Jest 。
将插件安装为开发依赖项后,我根据插件自述文件中的说明将以下内容合并到我的 .eslintrc 配置文件中。
{
"extends": ["plugin:jest/recommended"],
"plugins": ["jest"]
}
然后 no-undef 错误消失了。
因为我使用的是 StandardJS Linter,所以建议的解决方案都不适合我。 相反,我必须在我的标准配置中为“它”定义一个全局变量。
例如在package.json
中:
...
"standard": {
"parser": "babel-eslint",
"globals": [
"afterAll",
"beforeAll",
"afterEach",
"jasmine",
"describe",
"test",
"jest",
"expect",
"it"
]
}
...
该环境也可以应用于单个文件(无需修改配置文件)。
例如,在文件顶部使用此注释:
/* eslint-env jest */
当有一些文件(例如jest.setup.js
)访问jest.
并且在常规测试文件夹之外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.