RuleTester class is used to test ESLint rules. It integrates with testing frameworks like Mocha and Jest to provide a structured way to write and run rule tests.
Constructor
Default configuration to use for all test cases.
Instance Methods
run()
Runs test cases for a rule.The name of the rule being tested.
The rule object with a
create() method.Test Case Types
ValidTestCase
A test case expected to pass without errors.The code to test.
Name for the test case (displayed in test output).
Options to pass to the rule.
Language options for this test case.
Settings for this test case.
The fake filename for the test case.
Run only this test case (requires framework support).
InvalidTestCase
A test case expected to produce errors.The code to test.
Expected errors. Can be a count or array of error objects.
Expected code after autofixes. Use
null to assert no autofix.Name for the test case.
Options to pass to the rule.
Language options for this test case.
Settings for this test case.
The fake filename for the test case.
Run only this test case.
TestCaseError
Describes an expected error in an invalid test case.Expected error message or pattern.
Expected message ID from rule’s
meta.messages.Expected data used to fill the message template.
Expected 1-based line number.
Expected 1-based column number.
Expected 1-based end line number.
Expected 1-based end column number.
Expected suggestion objects.
Static Methods
RuleTester.setDefaultConfig()
Sets the default configuration for all RuleTester instances.The default configuration object.
RuleTester.resetDefaultConfig()
Resets the default configuration to the initial defaults.RuleTester.describe()
Sets the describe function for grouping tests (automatically detected).The describe function from your test framework.
RuleTester.it()
Sets the it function for individual tests (automatically detected).The it function from your test framework.
Examples
- Basic Test
- With Message IDs
- With Options
- With Suggestions
Best Practices
Use Named Test Cases
Add aname property to test cases for better test output:
Test All Error Properties
Verify message IDs, data, and locations:Test Autofixes
Always specify the expectedoutput for fixable rules:
Use Null for No Autofix
Setoutput: null to assert the rule doesn’t provide a fix: