【问题标题】:How to use ESLint with Jest如何在 Jest 中使用 ESLint
【发布时间】:2015-10-16 05:44:52
【问题描述】:

我正在尝试将 ESLint linter 与 Jest 测试框架一起使用。

Jest 测试使用jest 之类的全局变量运行,我需要告诉 linter;但棘手的是目录结构,在 Jest 中,测试与源代码一起嵌入在 __tests__ 文件夹中,因此目录结构类似于:

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

通常,我会将所有测试都放在一个目录下,我可以在其中添加一个 .eslintrc 文件来添加全局变量...但我当然不想添加一个 .eslintrc 文件到每个__test__ 目录。

目前,我刚刚将测试全局变量添加到全局 .eslintrc 文件中,但这意味着我现在可以在非测试代码中引用 jest,这似乎不是“正确”的解决方案.

有没有办法让 eslint 应用基于目录名称的某种模式的规则,或者类似的东西?

【问题讨论】:

  • 这对于实际答案来说有点太暴力了,但是您可以有一个单独的 linting 任务,手动使用带有 glob 的eslint-test 文件,例如eslint **/__tests__/*.js -c eslint-test.yml。也就是说,我不认为 jestbeforeEach 全局泄漏到生产代码中的危险;)

标签: javascript jestjs eslint


【解决方案1】:

The docs 表明您现在可以添加:

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

到您的.eslintrc,它将向您的环境添加所有与开玩笑相关的内容,消除 linter 错误/警告。

您可能需要将 plugins: ["jest"] 包含到您的 esconfig 中,如果仍然无法正常工作,请添加 eslint-plugin-jest 插件。

【讨论】:

  • 使用此方法,在匹配“.test.js”或“__tests__/.js”模式的文件之外使用“describe”或“it”将不会导致 linting 错误。有什么办法可以实现吗?
  • @l0rin 您可以在__tests__ 文件夹中添加一个扩展您默认.eslintrc.eslintrc 文件。如果您遇到与 OP 相同的问题(多个测试文件夹),那么您可以使用模板和小型 bash 脚本(类似于ls **/__tests/ | xargs cp templates/.eslintrc)生成那些 .eslintrc
  • 相关链接here
  • 这仍然准确吗?文档特别说 "jest/globals": true 而不是 "jest": true
  • @Sawtaytoes 好地方。我已经相应地更新了答案:)
【解决方案2】:

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

这是 eslint config 的“扩展覆盖”限制的解决方法(从这里的另一个答案,投票!):

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

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

【讨论】:

  • 谢谢,这完全是解决这个问题的正确方法,因为它确实回答了这个问题。为我工作!
  • 这太棒了!通过将我的 ESLint 更新到版本 >= 4 并在 eslint.rc 中将 "files""env" 对象添加到 "overrides",我不再需要担心 Jest 特定语法在测试文件之外传递 linting。
  • 优秀的解决方案,当您具有非标准文件夹结构时,也适用于其他框架(茉莉花)。
  • 我是写接受答案的人 - 这个答案比我的要好得多!虽然在我写答案的时候,这是解决这个问题的唯一方法。
  • ESLint 现在支持扩展覆盖
【解决方案3】:

您还可以在测试文件中设置测试环境,如下所示:

/* eslint-env jest */

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

【讨论】:

    【解决方案4】:

    为了完成 Zachary 的回答,这里是 eslint config 的“扩展覆盖”限制的解决方法:

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

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

    【讨论】:

      【解决方案5】:

      我解决了问题REF

      运行

      # For Yarn
      yarn add eslint-plugin-jest -D
      
      # For NPM
      npm i eslint-plugin-jest -D
      

      然后添加您的.eslintrc 文件

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

      【讨论】:

        【解决方案6】:

        一些答案​​假设你已经安装了eslint-plugin-jest,但是不需要这样做,你可以简单地在你的.eslintrc 文件,添加

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

        【讨论】:

          【解决方案7】:

          基于模式的配置计划用于 ESLint 的 2.0.0 版本。但是,现在,您必须创建两个单独的任务(如 cmets 中所述)。一个用于测试,一个用于其余代码并运行它们,同时提供不同的 .eslintrc 文件。

          附:在 ESLint 的下一个版本中会有一个 jest 环境,它将注册所有必要的全局变量。

          【讨论】:

            【解决方案8】:

            从 ESLint V 6(2019 年底发布)开始,您可以在基于 glob 的配置中使用 extends,如下所示:

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

            【讨论】:

              【解决方案9】:

              截至 2021 年,我认为正确的方法或至少可行的方法是安装 @types/jesteslint-plugin-jest

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

              并使用@Loren 提到的覆盖指令将 Jest 插件添加到 .eslintrc.js

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

              这样,您的源文件和测试文件中都会出现 linting 错误,但在测试文件中,test 和其他 Jest 函数不会出现 linting 错误,但是您会在源文件中将它们作为它们将在那里显示为未定义。

              【讨论】:

                【解决方案10】:

                仅为__tests__ 文件夹添加环境

                您可以在您的__tests__ 文件夹中添加一个.eslintrc.yml 文件,以扩展您的基本配置:

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

                如果您只有一个 __tests__folder,则此解决方案是最好的,因为它仅将 jest 环境限定在需要的地方。

                处理许多测试文件夹

                如果您有更多测试文件夹(OP 案例),我仍然建议添加这些文件。如果您有大量这些文件夹,可以使用简单的 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
                

                此脚本将查找__tests__ 文件夹并添加一个.eslintrc.yml 文件,配置如上所示。此脚本必须在包含您的父级 .eslintrc 的文件夹中启动。

                【讨论】:

                  【解决方案11】:

                  首先安装eslint-plugin-jest

                  跑步:

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

                  然后编辑 .eslintrc.json

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

                  【讨论】:

                    【解决方案12】:

                    我花了一些时间尝试不同的选项后让它运行起来。希望这可以帮助其他人陷入困境。

                    .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"
                        ]
                    }
                    

                    空的.babelrc(在根项目文件夹中):

                    {}
                    

                    .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(编辑器配置:启用自动修复保存+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"
                        ]
                    

                    【讨论】:

                      【解决方案13】:

                      在您的 .eslintignore 文件中添加以下值:

                      **/__tests__/
                      

                      这应该忽略 __tests__ 目录及其子目录的所有实例。

                      【讨论】:

                      • 这不是我想要的,我不想忽略测试文件,我仍然想对它们进行 lint,我只想弄清楚如何指定必要的选项来正确地对它们进行 lint。
                      • 非常糟糕的主意,eslint 对所有代码都有帮助——包括测试代码。
                      猜你喜欢
                      • 1970-01-01
                      • 2015-06-17
                      • 2021-02-01
                      • 2020-04-07
                      • 2015-05-06
                      • 2017-07-18
                      • 2017-07-29
                      • 1970-01-01
                      • 2015-08-14
                      相关资源
                      最近更新 更多