Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

eslint

chai

In my Chai tests I often find myself wanting to use their assertions that are something like .to.be.empty, .to.be.true e.t.c., because I find them to be cleaner to read than .to.be.length(1) or .to.be.equal(true). However, this breaks my linter (I'm using default Airbnb linting).

I could use the // disable-eslint-line syntax, but then I'd have to add it to every single line that reads like that and that seems tedious.

I've also read about the DirtyChai library, but that would require me to go back through my entire testing library adding brackets to them all which seems like something I shouldn't have to do simply to get my linter to pass something it should probably be OK with in the first place.

Does anyone know a nicer way to handle this than the ways I've outlined above?

like image 283
Ben Hare Avatar asked Jun 01 '16 03:06

Ben Hare


People also ask

How do you ignore ESLint rule?

log() statements that ESLint doesn't like. To temporarily turn off ESLint, you should add a block comment /* eslint-disable */ before the lines that you're interested in: /* eslint-disable */ console.


2 Answers

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.

like image 139
Nick Bartlett Avatar answered Oct 03 '22 10:10

Nick Bartlett


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.

like image 43
Ihor Diachenko Avatar answered Oct 03 '22 11:10

Ihor Diachenko