简体   繁体   English

如何在 Jest 中使用 ESLint

[英]How to use ESLint with Jest

I'm attempting to use the ESLint linter with the Jest testing framework.我正在尝试将 ESLint linter 与 Jest 测试框架一起使用。

Jest tests run with some globals like jest , which I'll need to tell the linter about; Jest 测试与一些全局变量一起运行,比如jest ,我需要告诉 linter ; but the tricky thing is the directory structure, with Jest the tests are embedded with the source code in __tests__ folders, so the directory structure looks something like:但棘手的是目录结构,在 Jest 中,测试与__tests__文件夹中的源代码一起__tests__ ,因此目录结构如下所示:

src
    foo
        foo.js
        __tests__
            fooTest.js
    bar
        bar.js
        __tests__
            barTest.js

Normally, I'd have all my tests under a single dir, and I could just add an .eslintrc file there to add the globals... but I certainly don't want to add a .eslintrc file to every single __test__ dir.通常,我会将所有测试都放在一个目录下,我可以在那里添加一个.eslintrc文件来添加全局变量……但我当然不想将.eslintrc文件添加到每个__test__目录中。

For now, I've just added the test globals to the global .eslintrc file, but since that means I could now reference jest in non-testing code, that doesn't seem like the "right" solution.目前,我刚刚将测试全局变量添加到全局.eslintrc文件中,但由于这意味着我现在可以在非测试代码中引用jest ,这似乎不是“正确”的解决方案。

Is there a way to get eslint to apply rules based on some pattern based on the directory name, or something like that?有没有办法让 eslint 应用基于目录名称的某种模式的规则,或者类似的东西?

The docs show you are now able to add:文档显示您现在可以添加:

"env": {
    "jest/globals": true
}

To your .eslintrc which will add all the jest related things to your environment, eliminating the linter errors/warnings.到您的.eslintrc ,它将向您的环境添加所有与开玩笑相关的内容,消除 linter 错误/警告。

You may need to include plugins: ["jest"] to your esconfig, and add the eslint-plugin-jest plugin if it still isn't working.您可能需要将plugins: ["jest"]到您的 esconfig 中,如果仍然无法正常工作,请添加eslint-plugin-jest插件。

ESLint supports this as of version >= 4: ESLint 从版本 >= 4 开始支持这个:

/*
.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"
      }
    }
  ],
};

Here is a workaround (from another answer on here, vote it up!) for the "extend in overrides" limitation of eslint config :这是针对 eslint config 的“扩展覆盖”限制的解决方法(来自此处的另一个答案,请投票!):

overrides: [
  Object.assign(
    {
      files: [ '**/*.test.js' ],
      env: { jest: true },
      plugins: [ 'jest' ],
    },
    require('eslint-plugin-jest').configs.recommended
  )
]

From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724来自https://github.com/eslint/eslint/issues/8813#issuecomment-320448724

You can also set the test env in your test file as follows:您还可以在测试文件中设置测试环境,如下所示:

/* eslint-env jest */

describe(() => {
  /* ... */
})

To complete Zachary's answer, here is a workaround for the "extend in overrides" limitation of eslint config :要完成 Zachary 的回答,这里是 eslint config 的“扩展覆盖”限制的解决方法:

overrides: [
  Object.assign(
    {
      files: [ '**/*.test.js' ],
      env: { jest: true },
      plugins: [ 'jest' ],
    },
    require('eslint-plugin-jest').configs.recommended
  )
]

From https://github.com/eslint/eslint/issues/8813#issuecomment-320448724来自https://github.com/eslint/eslint/issues/8813#issuecomment-320448724

I solved the problem REF我解决了问题REF

Run

# For Yarn
yarn add eslint-plugin-jest -D

# For NPM
npm i eslint-plugin-jest -D

And then add in your .eslintrc file然后添加你的.eslintrc文件

{
    "extends": ["airbnb","plugin:jest/recommended"],
}

Pattern based configs are scheduled for 2.0.0 release of ESLint.基于模式的配置计划用于 ESLint 2.0.0 版本。 For now, however, you will have to create two separate tasks (as mentioned in the comments).但是,现在您必须创建两个单独的任务(如评论中所述)。 One for tests and one for the rest of the code and run both of them, while providing different .eslintrc files.一个用于测试,一个用于其余代码并运行它们,同时提供不同的 .eslintrc 文件。

PS There's a jest environment coming in the next release of ESLint, it will register all of the necessary globals. PS 在 ESLint 的下一个版本中会有一个 jest 环境,它将注册所有必要的全局变量。

some of the answers assume you have eslint-plugin-jest installed, however without needing to do that, you can simply do this in your .eslintrc file, add :一些答案假设您安装了eslint-plugin-jest ,但是无需这样做,您只需在.eslintrc文件中执行操作,添加

  "globals": {
    "jest": true,
  }

Add environment only for __tests__ folder仅为__tests__文件夹添加环境

You could add a .eslintrc.yml file in your __tests__ folders, that extends you basic configuration:您可以在__tests__文件夹中添加一个.eslintrc.yml文件,以扩展您的基本配置:

extends: <relative_path to .eslintrc>
env:
    jest: true

If you have only one __tests__ folder, this solution is the best since it scope jest environment only where it is needed.如果你只有一个__tests__文件夹,这个解决方案是最好的,因为它只在需要的地方__tests__ jest 环境。

Dealing with many test folders处理许多测试文件夹

If you have more test folders (OPs case), I'd still suggest to add those files.如果您有更多测试文件夹(OP 案例),我仍然建议添加这些文件。 And if you have tons of those folders can add them with a simple zsh script:如果您有大量这些文件夹,可以使用简单的 zsh 脚本添加它们:

#!/usr/bin/env zsh

for folder in **/__tests__/ ;do
    count=$(($(tr -cd '/' <<< $folder | wc -c)))
    echo $folder : $count
    cat <<EOF > $folder.eslintrc.yml
extends: $(printf '../%.0s' {1..$count}).eslintrc
env:
    jest: true
EOF
done

This script will look for __tests__ folders and add a .eslintrc.yml file with to configuration shown above.该脚本将寻找__tests__文件夹,并添加.eslintrc.yml文件,上面显示的配置。 This script has to be launched within the folder containing your parent .eslintrc .此脚本必须在包含您的父.eslintrc的文件夹中.eslintrc

I got it running after spending some time trying out different options.我花了一些时间尝试不同的选项后让它运行。 Hope this helps anyone else getting stuck.希望这可以帮助其他人陷入困境。

.eslintrc.json (in root project folder): .eslintrc.json(在根项目文件夹中):

{
    "env": {
        "browser": true,
        "es2021": true,
        "jest/globals": true
    },
    "extends": [
        "standard",
        "plugin:jest/all"
    ],
    "parser": "@babel/eslint-parser",
    "parserOptions": {
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "rules": {
        "jest/no-hooks": [
            "error",
            {
                "allow": [
                    "afterEach",
                    "beforeEach"
                ]
            }
        ]
    },
    "plugins": [
        "jest"
    ]
}

Empty .babelrc (in root project folder):空 .babelrc (在根项目文件夹中):

{}

.package.json (in root project folder): .package.json(在根项目文件夹中):

{
  "scripts": {
    "test": "jest",
    "lint": "npx eslint --format=table .",
    "lintfix": "npx eslint --fix ."
  },
  "devDependencies": {
    "@babel/core": "^7.15.0",
    "@babel/eslint-parser": "^7.15.0",
    "aws-sdk-mock": "^5.2.1",
    "eslint": "^7.32.0",
    "eslint-config-standard": "^16.0.3",
    "eslint-plugin-import": "^2.24.0",
    "eslint-plugin-jest": "^24.4.0",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^5.1.0",
    "jest": "^27.0.6"
  }
}

VS Code settings.xml (editor configuration: enables auto fix on save + babel parser): VS Code settings.xml(编辑器配置:启用自动修复保存 + babel 解析器):

    "eslint.alwaysShowStatus": true,
    "eslint.format.enable": true,
    "eslint.lintTask.enable": true,
    "eslint.options": {
        "parser": "@babel/eslint-parser"
    },
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true
    },
    "eslint.validate": [
        "javascript"
    ]

First install eslint-plugin-jest首先安装eslint-plugin-jest

Running:跑步:

 yarn add eslint-plugin-jest or npm install eslint-plugin-jest

Then edit .eslintrc.json然后编辑.eslintrc.json

{
   "env":{
     "jest": true
   }
}

As of ESLint V 6 (released in late 2019), you can use extends in the glob based config as follows:从 ESLint V 6(2019 年末发布)开始,您可以在基于 glob 的配置中使用扩展,如下所示:

    "overrides": [
      {
        "files": ["*.test.js"],
        "env": {
          "jest": true
        },
        "plugins": ["jest"],
        "extends": ["plugin:jest/recommended"]
      }
    ]

As of 2021, I think the correct way or at least the one that works is to install @types/jest and eslint-plugin-jest :到 2021 年,我认为正确的方法或至少有效的方法是安装@types/jesteslint-plugin-jest

npm i -D eslint-plugin-jest @types/jest

And adding the Jest plugin into .eslintrc.js with the overrides instruction mentioned by @Loren:并使用.eslintrc.js提到的覆盖指令将 Jest 插件添加到.eslintrc.js中:

module.exports = {
  ...
  plugins: ["jest"],
  ...
  overrides: [
    {
      files: ["**/*.test.js"],
      env: { "jest/globals": true },
      plugins: ["jest"],
      extends: ["plugin:jest/recommended"],
    },
  ],
  ...
};

This way you get linting errors in your source files as well as in test files, but in test files you don't get linting errors for test and other Jest's functions, but you will get them in your source files as they will appear as undefined there.这样你会在源文件和测试文件中得到 linting 错误,但在测试文件中你不会得到test和其他 Jest 函数的 linting 错误,但是你会在源文件中得到它们,因为它们会显示为未定义那里。

In your .eslintignore file add the following value:在您的 .eslintignore 文件中添加以下值:

**/__tests__/

This should ignore all instances of the __tests__ directory and their children.这应该忽略 __tests__ 目录及其子目录的所有实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM