-
Notifications
You must be signed in to change notification settings - Fork 237
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: create
prefer-equality-matcher
rule (#1016)
- Loading branch information
Showing
6 changed files
with
325 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
# Suggest using the built-in equality matchers (`prefer-equality-matcher`) | ||
|
||
Jest has built-in matchers for expecting equality which allow for more readable | ||
tests and error messages if an expectation fails. | ||
|
||
## Rule details | ||
|
||
This rule checks for _strict_ equality checks (`===` & `!==`) in tests that | ||
could be replaced with one of the following built-in equality matchers: | ||
|
||
- `toBe` | ||
- `toEqual` | ||
- `toStrictEqual` | ||
|
||
Examples of **incorrect** code for this rule: | ||
|
||
```js | ||
expect(x === 5).toBe(true); | ||
expect(name === 'Carl').not.toEqual(true); | ||
expect(myObj !== thatObj).toStrictEqual(true); | ||
``` | ||
|
||
Examples of **correct** code for this rule: | ||
|
||
```js | ||
expect(x).toBe(5); | ||
expect(name).not.toEqual('Carl'); | ||
expect(myObj).toStrictEqual(thatObj); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,155 @@ | ||
import { TSESLint } from '@typescript-eslint/experimental-utils'; | ||
import rule from '../prefer-equality-matcher'; | ||
import { espreeParser } from './test-utils'; | ||
|
||
const ruleTester = new TSESLint.RuleTester({ | ||
parser: espreeParser, | ||
parserOptions: { | ||
ecmaVersion: 2015, | ||
}, | ||
}); | ||
|
||
type RuleMessages<TRuleModule extends TSESLint.RuleModule<string>> = | ||
TRuleModule extends TSESLint.RuleModule<infer TMessageIds> | ||
? TMessageIds | ||
: never; | ||
|
||
type RuleSuggestionOutput = TSESLint.SuggestionOutput< | ||
RuleMessages<typeof rule> | ||
>; | ||
|
||
const expectSuggestions = ( | ||
output: (equalityMatcher: string) => string, | ||
): RuleSuggestionOutput[] => { | ||
return ['toBe', 'toEqual', 'toStrictEqual'].map<RuleSuggestionOutput>( | ||
equalityMatcher => ({ | ||
messageId: 'suggestEqualityMatcher', | ||
data: { equalityMatcher }, | ||
output: output(equalityMatcher), | ||
}), | ||
); | ||
}; | ||
|
||
ruleTester.run('prefer-equality-matcher: ===', rule, { | ||
valid: [ | ||
'expect(a == 1).toBe(true)', | ||
'expect(1 == a).toBe(true)', | ||
'expect(a == b).toBe(true)', | ||
], | ||
invalid: [ | ||
{ | ||
code: 'expect(a === b).toBe(true);', | ||
errors: [ | ||
{ | ||
messageId: 'useEqualityMatcher', | ||
suggestions: expectSuggestions( | ||
equalityMatcher => `expect(a).${equalityMatcher}(b);`, | ||
), | ||
column: 17, | ||
line: 1, | ||
}, | ||
], | ||
}, | ||
{ | ||
code: 'expect(a === b).toBe(false);', | ||
errors: [ | ||
{ | ||
messageId: 'useEqualityMatcher', | ||
suggestions: expectSuggestions( | ||
equalityMatcher => `expect(a).not.${equalityMatcher}(b);`, | ||
), | ||
column: 17, | ||
line: 1, | ||
}, | ||
], | ||
}, | ||
{ | ||
code: 'expect(a === b).not.toBe(true);', | ||
errors: [ | ||
{ | ||
messageId: 'useEqualityMatcher', | ||
suggestions: expectSuggestions( | ||
equalityMatcher => `expect(a).not.${equalityMatcher}(b);`, | ||
), | ||
column: 17, | ||
line: 1, | ||
}, | ||
], | ||
}, | ||
{ | ||
code: 'expect(a === b).not.toBe(false);', | ||
errors: [ | ||
{ | ||
messageId: 'useEqualityMatcher', | ||
suggestions: expectSuggestions( | ||
equalityMatcher => `expect(a).${equalityMatcher}(b);`, | ||
), | ||
column: 17, | ||
line: 1, | ||
}, | ||
], | ||
}, | ||
], | ||
}); | ||
|
||
ruleTester.run('prefer-equality-matcher: !==', rule, { | ||
valid: [ | ||
'expect(a != 1).toBe(true)', | ||
'expect(1 != a).toBe(true)', | ||
'expect(a != b).toBe(true)', | ||
], | ||
invalid: [ | ||
{ | ||
code: 'expect(a !== b).toBe(true);', | ||
errors: [ | ||
{ | ||
messageId: 'useEqualityMatcher', | ||
suggestions: expectSuggestions( | ||
equalityMatcher => `expect(a).not.${equalityMatcher}(b);`, | ||
), | ||
column: 17, | ||
line: 1, | ||
}, | ||
], | ||
}, | ||
{ | ||
code: 'expect(a !== b).toBe(false);', | ||
errors: [ | ||
{ | ||
messageId: 'useEqualityMatcher', | ||
suggestions: expectSuggestions( | ||
equalityMatcher => `expect(a).${equalityMatcher}(b);`, | ||
), | ||
column: 17, | ||
line: 1, | ||
}, | ||
], | ||
}, | ||
{ | ||
code: 'expect(a !== b).not.toBe(true);', | ||
errors: [ | ||
{ | ||
messageId: 'useEqualityMatcher', | ||
suggestions: expectSuggestions( | ||
equalityMatcher => `expect(a).${equalityMatcher}(b);`, | ||
), | ||
column: 17, | ||
line: 1, | ||
}, | ||
], | ||
}, | ||
{ | ||
code: 'expect(a !== b).not.toBe(false);', | ||
errors: [ | ||
{ | ||
messageId: 'useEqualityMatcher', | ||
suggestions: expectSuggestions( | ||
equalityMatcher => `expect(a).not.${equalityMatcher}(b);`, | ||
), | ||
column: 17, | ||
line: 1, | ||
}, | ||
], | ||
}, | ||
], | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,138 @@ | ||
import { | ||
AST_NODE_TYPES, | ||
TSESLint, | ||
TSESTree, | ||
} from '@typescript-eslint/experimental-utils'; | ||
import { | ||
MaybeTypeCast, | ||
ModifierName, | ||
ParsedEqualityMatcherCall, | ||
ParsedExpectMatcher, | ||
createRule, | ||
followTypeAssertionChain, | ||
isExpectCall, | ||
isParsedEqualityMatcherCall, | ||
parseExpectCall, | ||
} from './utils'; | ||
|
||
const isBooleanLiteral = ( | ||
node: TSESTree.Node, | ||
): node is TSESTree.BooleanLiteral => | ||
node.type === AST_NODE_TYPES.Literal && typeof node.value === 'boolean'; | ||
|
||
type ParsedBooleanEqualityMatcherCall = ParsedEqualityMatcherCall< | ||
MaybeTypeCast<TSESTree.BooleanLiteral> | ||
>; | ||
|
||
/** | ||
* Checks if the given `ParsedExpectMatcher` is a call to one of the equality matchers, | ||
* with a boolean literal as the sole argument. | ||
* | ||
* @example javascript | ||
* toBe(true); | ||
* toEqual(false); | ||
* | ||
* @param {ParsedExpectMatcher} matcher | ||
* | ||
* @return {matcher is ParsedBooleanEqualityMatcher} | ||
*/ | ||
const isBooleanEqualityMatcher = ( | ||
matcher: ParsedExpectMatcher, | ||
): matcher is ParsedBooleanEqualityMatcherCall => | ||
isParsedEqualityMatcherCall(matcher) && | ||
isBooleanLiteral(followTypeAssertionChain(matcher.arguments[0])); | ||
|
||
export default createRule({ | ||
name: __filename, | ||
meta: { | ||
docs: { | ||
category: 'Best Practices', | ||
description: 'Suggest using the built-in equality matchers', | ||
recommended: false, | ||
suggestion: true, | ||
}, | ||
messages: { | ||
useEqualityMatcher: 'Prefer using one of the equality matchers instead', | ||
suggestEqualityMatcher: 'Use `{{ equalityMatcher }}`', | ||
}, | ||
hasSuggestions: true, | ||
type: 'suggestion', | ||
schema: [], | ||
}, | ||
defaultOptions: [], | ||
create(context) { | ||
return { | ||
CallExpression(node) { | ||
if (!isExpectCall(node)) { | ||
return; | ||
} | ||
|
||
const { | ||
expect: { | ||
arguments: [comparison], | ||
range: [, expectCallEnd], | ||
}, | ||
matcher, | ||
modifier, | ||
} = parseExpectCall(node); | ||
|
||
if ( | ||
!matcher || | ||
comparison?.type !== AST_NODE_TYPES.BinaryExpression || | ||
(comparison.operator !== '===' && comparison.operator !== '!==') || | ||
!isBooleanEqualityMatcher(matcher) | ||
) { | ||
return; | ||
} | ||
|
||
const matcherValue = followTypeAssertionChain( | ||
matcher.arguments[0], | ||
).value; | ||
|
||
// we need to negate the expectation if the current expected | ||
// value is itself negated by the "not" modifier | ||
const addNotModifier = | ||
(comparison.operator === '!==' ? !matcherValue : matcherValue) === | ||
!!modifier; | ||
|
||
const buildFixer = | ||
(equalityMatcher: string): TSESLint.ReportFixFunction => | ||
fixer => { | ||
const sourceCode = context.getSourceCode(); | ||
|
||
return [ | ||
// replace the comparison argument with the left-hand side of the comparison | ||
fixer.replaceText( | ||
comparison, | ||
sourceCode.getText(comparison.left), | ||
), | ||
// replace the current matcher & modifier with the preferred matcher | ||
fixer.replaceTextRange( | ||
[expectCallEnd, matcher.node.range[1]], | ||
addNotModifier | ||
? `.${ModifierName.not}.${equalityMatcher}` | ||
: `.${equalityMatcher}`, | ||
), | ||
// replace the matcher argument with the right-hand side of the comparison | ||
fixer.replaceText( | ||
matcher.arguments[0], | ||
sourceCode.getText(comparison.right), | ||
), | ||
]; | ||
}; | ||
|
||
context.report({ | ||
messageId: 'useEqualityMatcher', | ||
suggest: ['toBe', 'toEqual', 'toStrictEqual'].map( | ||
equalityMatcher => ({ | ||
messageId: 'suggestEqualityMatcher', | ||
data: { equalityMatcher }, | ||
fix: buildFixer(equalityMatcher), | ||
}), | ||
), | ||
node: (modifier || matcher).node.property, | ||
}); | ||
}, | ||
}; | ||
}, | ||
}); |