This video is available to students only

Testing custom linting rules

Testing custom ESLint linting rules to verify they work as expected

Testing custom ESLint rules has similar benefits to testing a custom jscodeshift transform. First, taking a test-driven approach when creating custom rules can offer a faster feedback loop. The tests run significantly faster than trying to run them on an entire codebase. Second, if the rule is complex or shared across many different codebases, tests can help provide confidence that the rule is working as intended.

Testing a rule#

To get started, create a new file no-button-element.test.js alongside the rule in the eslint-rules directory, with an import for the rule and the RuleTester utility from ESLint.

The rule tester uses the default ESLint configuration (not the one provided by Create React App) so any necessary configuration also needs to be passed to the RuleTester when initialized. By default, ESLint only expects ES5 syntax. In this case, only the parser options need to be specified to enable JSX support (eg: <button>) otherwise the ESLint parser will throw an invalid syntax error.

Then, the test cases can be defined and run. The RuleTester has a run method to execute tests. It expects three arguments: the rule name, the rule definition, and test cases.

 

This page is a preview of Practical Abstract Syntax Trees

Start a new discussion. All notification go to the author.