Ret*_*sam 196 javascript eslint jestjs
我正在尝试将ESLint linter与Jest测试框架一起使用.
Jest测试用一些全局变量运行jest,我需要告诉linter; 但是棘手的是目录结构,使用Jest测试嵌入了__tests__文件夹中的源代码,因此目录结构类似于:
src
foo
foo.js
__tests__
fooTest.js
bar
bar.js
__tests__
barTest.js
Run Code Online (Sandbox Code Playgroud)
通常情况下,我在单个目录下进行所有测试,我可以在.eslintrc那里添加一个文件来添加全局...但我当然不想.eslintrc在每个__test__目录中添加一个文件.
现在,我刚刚将测试全局变量添加到全局.eslintrc文件中,但由于这意味着我现在可以jest在非测试代码中引用,这似乎不是"正确"的解决方案.
有没有办法让eslint基于某些基于目录名称的模式应用规则,或类似的东西?
Dav*_*per 537
文档显示您现在可以添加:
"env": {
"jest": true
}
Run Code Online (Sandbox Code Playgroud)
您.eslintrc将为您的环境添加所有相关内容,消除linter错误/警告.
希望有所帮助!
Zac*_*ith 55
从版本> = 4开始,ESLint支持此功能:
/*
.eslintrc.js
*/
const ERROR = 2;
const WARN = 1;
module.exports = {
extends: "eslint:recommended",
env: {
es6: true
},
overrides: [
{
files: [
"**/*.test.js"
],
env: {
jest: true // now **/*.test.js files' env has both es6 *and* jest
},
// Can't extend in overrides: https://github.com/eslint/eslint/issues/8813
// "extends": ["plugin:jest/recommended"]
plugins: ["jest"],
rules: {
"jest/no-disabled-tests": "warn",
"jest/no-focused-tests": "error",
"jest/no-identical-title": "error",
"jest/prefer-to-have-length": "warn",
"jest/valid-expect": "error"
}
}
],
};
Run Code Online (Sandbox Code Playgroud)
这是一个解决方法(来自这里的另一个答案,投票了!)用于eslint配置的"覆盖范围扩展"限制:
overrides: [
Object.assign(
{
files: [ '**/*.test.js' ],
env: { jest: true },
plugins: [ 'jest' ],
},
require('eslint-plugin-jest').configs.recommended
)
]
Run Code Online (Sandbox Code Playgroud)
来自https://github.com/eslint/eslint/issues/8813#issuecomment-320448724
HaN*_*riX 14
您还可以在测试文件中设置测试环境,如下所示:
/* eslint-env jest */
describe(() => {
/* ... */
})
Run Code Online (Sandbox Code Playgroud)
ton*_*nix 14
截至 2021 年,我认为正确的方法或至少有效的方法是安装@types/jest和eslint-plugin-jest:
npm i -D eslint-plugin-jest @types/jest
Run Code Online (Sandbox Code Playgroud)
并将 Jest 插件添加到.eslintrc.js@Loren 提到的覆盖指令中:
npm i -D eslint-plugin-jest @types/jest
Run Code Online (Sandbox Code Playgroud)
这样你就可以在源文件和测试文件中得到 linting 错误,但在测试文件中,你不会得到test和其他 Jest 函数的 linting 错误,但你会在源文件中得到它们,因为它们在那里显示为未定义。 。
Ric*_*tch 11
要完成Zachary的答案,以下是eslint配置中"覆盖范围扩展"限制的解决方法:
overrides: [
Object.assign(
{
files: [ '**/*.test.js' ],
env: { jest: true },
plugins: [ 'jest' ],
},
require('eslint-plugin-jest').configs.recommended
)
]
Run Code Online (Sandbox Code Playgroud)
来自https://github.com/eslint/eslint/issues/8813#issuecomment-320448724
小智 9
我解决了问题REF
跑
# For Yarn
yarn add eslint-plugin-jest -D
# For NPM
npm i eslint-plugin-jest -D
Run Code Online (Sandbox Code Playgroud)
然后在你的.eslintrc文件中添加
{
"extends": ["airbnb","plugin:jest/recommended"],
}
Run Code Online (Sandbox Code Playgroud)
小智 5
首先安装eslint-plugin-jest
跑步:
yarn add eslint-plugin-jest
Run Code Online (Sandbox Code Playgroud)
或者
npm install eslint-plugin-jest
Run Code Online (Sandbox Code Playgroud)
然后编辑.eslintrc.json
{
"env":{
"jest": true
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70419 次 |
| 最近记录: |