Riding rough-shod over your eslint rules
18th April, 2019
2 min read
In HMH we have adopted fairly strict eslint rules regarding code complexity. I've written about eslint complexity metrics before, and will no doubt do so again! The rules work well for our code, but do tend to get in the way when we are writing tests.
Tests need code standards too!
I'm not saying you should abandon all pretense to code standards for unit test code, but by their nature tests are often larger, more verbose, and complex than the code they are targeting. We've adopted a few approaches to try and keep the tests flexible and maintainable by breaking them into multiple files, adding a dash of SOLID principles and generally using our common sense.
Even with all that, our test files are a mess of squiggly green lines telling us we have failed to write cromulent code. If only we could relax the rules for our test code!
Overrides to the rescue
Luckily, we can indeed have eslint apply different rules to different files.
For us, we know that the test files are consistently named somemodule.test.js
so the associated eslint config will be:
{
"rules": {
/* rules here will apply to all files */
"complexity": [
"error",
6
],
"max-nested-callbacks": [
"error",
2
],
"max-lines": [
"warn",
80
],
},
"overrides": [
{
"files": ["*.test.js"],
"rules": {
// we've changed all the errors to warnings
// and relaxed the rules
"complexity": [
"warn",
12
],
"max-nested-callbacks": [
"warn",
5
],
"max-lines": [
"warn",
200
],
}
},
{
"files": ["*.any.other.files.js"],
"rules": {
/* add suitable rule configs here */
}
}
]
}
As you can see you can have multiple overrides for different file types, although we only override the unit test rules.