使用 chai 消除 no-unused-expressions linter 错误的好方法

Nice way to get rid of no-unused-expressions linter error with chai

在我的 Chai 测试中,我经常发现自己想要使用他们的断言,例如 .to.be.empty.to.be.true e.t.c.,因为我发现它们比阅读起来更清晰.to.be.length(1).to.be.equal(true)。但是,这会破坏我的 linter(我使用的是默认的 Airbnb linting)。

我可以使用 // disable-eslint-line 语法,但我必须将它添加到每一行,这样看起来很乏味。

我也读过 DirtyChai 库,但这需要我回顾我的整个测试库,为它们添加括号,这似乎是我不应该简单地做的事情让我的 linter 传递一些它应该首先可以接受的东西。

有没有人知道比我上面概述的方法更好的处理方法?

您可以使用相关文件顶部的 eslint-disable 禁用整个文件的规则:

/* eslint-disable no-unused-expressions */
expect(someTrueValue).to.be.true; 

但是,将它添加到每个测试文件的顶部可能会很乏味。要对所有相关文件禁用此规则,您可以:

  1. 放一个新的.eslintcconfiguration file in the same directory as your test files, configured to disable that rule. This allows you to use the default configuration for all other rules while ignoring that rule specifically only on files in that folder. ESLint calls this Configuration Cascading.

    {
        "rules": {
            "no-unused-expressions": "off"
        }
    }
    
  2. 使用主 .eslintrc 文件中的 overrides 键到 disable rules for groups of files 与 glob 模式匹配:

    {
        "overrides": [
            {
                "files": ["*.test.js", "*.spec.js"],
                "rules": {
                    "no-unused-expressions": "off"
                }
            }
        ]
    }
    

这还允许您禁用其他在测试中变得麻烦的规则,例如使用 rewire 时的 no-underscore-dangle

我做了一个名为 eslint-plugin-chai-friendly 的小 plugin,它覆盖了默认的 no-unused-expressions 规则并使其对 chai 友好。修改后的规则忽略 expectshould 语句,同时保持其他所有内容的默认行为。

刚刚使用 Relative Glob Patterns 找到了另一个选项:

在您的 .eslintrc 文件中:

overrides: [
    {
        files: "*.test.js",
        rules: {
          "no-unused-expressions": "off"
        }
    }
]

如果今天有人遇到这个问题,我遇到了同样的问题并在 eslint documentation 上找到了这个解决方案。在你的eslint配置文件中,你可以指定一个或几个环境,它会为这个环境预定义全局变量。对于我们来说,它是 mocha,您可以在 .eslintrc.json:

中这样配置
{
    "env": {
        "mocha": true
    },
    ...
    ...
    ...
}

因此,它将消除所有关于 mocha describeitbeforeEach 等的误报,而无需完全禁用 eslint 或完全禁用任何特定规则。

使用 ESLint v.4.11 和 mocha 5.0 测试

组合 with 给了我想要的东西:

npm install --save-dev eslint-plugin-chai-friendly

// .eslintrc.js
module.exports = {
  // ...
  plugins: ['chai-friendly'],
  overrides: [{
    files: '*.test.js',
    rules: {
      'no-unused-expressions': 'off',
      'chai-friendly/no-unused-expressions': 'error',
    },
  }],
  // ...
}

这样,no-unused-expression 规则只会在 *.test.js 个文件中被覆盖 和 no-unused-expression 规则仍然存在,以捕获测试文件中与 chai.

无关的任何未使用的表达式

我遇到了 tslint 的这个问题并通过简单地将未使用表达式的规则下移一级解决了它。我的 ./tslint.json 有我关心的所有其他规则,然后我制作了 ./src/tslint.json 看起来像

{
    "rules": {
        "no-unused-expression": true
    },
    "extends": "../tslint.json"
}

tslint 在树下降时自动检查每个级别的配置文件(使用 --project 或使用 VSCode 扩展名)所以这意味着我的测试(在 ./test/ ) 应用了所有其他规则,但 no-unused-expression 仅适用于 ./src/.

下的文件