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

You can disable the rule for the entire file using eslint-disable at the top of the file in question:

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

However, adding this at the top of every test file can be tedious. To disable this rule for all relevant files, you can:

  1. Put a new .eslintc configuration 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. Use the overrides key in your main .eslintrc file to disable rules for groups of files with glob pattern matching:

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

This also allows you to disable other rules which become troublesome in testing, such as no-underscore-dangle when using rewire.


I've made a small plugin called eslint-plugin-chai-friendly that overrides the default no-unused-expressions rule and makes it friendly towards chai. The modified rule ignores the expect and should statements while keeping default behavior for everything else.


Just found another option using Relative Glob Patterns:

In your .eslintrc file:

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

Combining jonalvarezz's answer with Ihor Diachenko's answer gave me exactly what I wanted:

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',
    },
  }],
  // ...
}

This way, the no-unused-expression rule will only be overridden in *.test.js files AND a no-unused-expression rule will still be in place to catch any unused expressions in the test files that are unrelated to chai.

Tags:

Chai

Eslint