-
Notifications
You must be signed in to change notification settings - Fork 22
feat(eslint-plugin-jest): add prefer-to-have-been-called rule
#1019
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
eryue0220
wants to merge
3
commits into
web-infra-dev:main
Choose a base branch
from
eryue0220:feat/jest-prefer-to-have-been-called
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+332
−59
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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
87 changes: 87 additions & 0 deletions
87
internal/plugins/jest/rules/prefer_to_have_been_called/prefer_to_have_been_called.go
This file contains hidden or 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,87 @@ | ||
| package prefer_to_have_been_called | ||
|
|
||
| import ( | ||
| "github.com/microsoft/typescript-go/shim/ast" | ||
| "github.com/microsoft/typescript-go/shim/core" | ||
| jestUtils "github.com/web-infra-dev/rslint/internal/plugins/jest/utils" | ||
| "github.com/web-infra-dev/rslint/internal/rule" | ||
| ) | ||
|
|
||
| // Message Builders | ||
|
|
||
| func buildPreferMatcherErrorMessage() rule.RuleMessage { | ||
| return rule.RuleMessage{ | ||
| Id: "preferMatcher", | ||
| Description: "Use `toHaveBeenCalled`", | ||
| } | ||
| } | ||
|
|
||
| func isZeroLiteral(node *ast.Node) bool { | ||
| node = jestUtils.UnwrapBasicTypeAssertions(node) | ||
| if node == nil { | ||
| return false | ||
| } | ||
|
|
||
| return node.Kind == ast.KindNumericLiteral && node.AsNumericLiteral().Text == "0" | ||
| } | ||
|
|
||
| var PreferToHaveBeenCalledRule = rule.Rule{ | ||
| Name: "jest/prefer-to-have-been-called", | ||
| Run: func(ctx rule.RuleContext, options any) rule.RuleListeners { | ||
| return rule.RuleListeners{ | ||
| ast.KindCallExpression: func(node *ast.Node) { | ||
| jestFnCall := jestUtils.ParseJestFnCall(node, ctx) | ||
| if jestFnCall == nil || | ||
| jestFnCall.Kind != jestUtils.JestFnTypeExpect || | ||
| (jestFnCall.Matcher != "toBeCalledTimes" && jestFnCall.Matcher != "toHaveBeenCalledTimes") { | ||
| return | ||
| } | ||
|
|
||
| matcherCall := node.AsCallExpression() | ||
| if matcherCall == nil || matcherCall.Arguments == nil || len(matcherCall.Arguments.Nodes) == 0 { | ||
| return | ||
| } | ||
|
|
||
| if !isZeroLiteral(matcherCall.Arguments.Nodes[0]) { | ||
| return | ||
| } | ||
|
|
||
| matcherReceiver, matcherParent := jestUtils.GetAccessorReceiverAndParent(jestFnCall.MatcherEntry) | ||
| if matcherParent == nil || matcherReceiver == nil { | ||
| return | ||
| } | ||
|
|
||
| var notModifier *jestUtils.ParsedJestFnMemberEntry | ||
| for i := range jestFnCall.ModifierEntries { | ||
| if jestFnCall.ModifierEntries[i].Name == "not" { | ||
| notModifier = &jestFnCall.ModifierEntries[i] | ||
| break | ||
| } | ||
| } | ||
|
|
||
| replaceStart := matcherReceiver.End() | ||
| if notModifier != nil { | ||
| notReceiver, _ := jestUtils.GetAccessorReceiverAndParent(notModifier) | ||
| if notReceiver == nil { | ||
| return | ||
| } | ||
| replaceStart = notReceiver.End() | ||
| } | ||
|
|
||
| replacementMatcher := ".not.toHaveBeenCalled" | ||
| if notModifier != nil { | ||
| replacementMatcher = ".toHaveBeenCalled" | ||
| } | ||
|
|
||
| ctx.ReportNodeWithFixes( | ||
| jestFnCall.MatcherEntry.Node, | ||
| buildPreferMatcherErrorMessage(), | ||
| rule.RuleFixReplaceRange( | ||
| core.NewTextRange(replaceStart, node.End()), | ||
| replacementMatcher+"()", | ||
| ), | ||
| ) | ||
| }, | ||
| } | ||
| }, | ||
| } | ||
30 changes: 30 additions & 0 deletions
30
...nal/plugins/jest/rules/prefer_to_have_been_called/prefer_to_have_been_called.md
This file contains hidden or 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,30 @@ | ||
| # prefer-to-have-been-called | ||
|
|
||
| ## Rule Details | ||
|
|
||
| In order to have a better failure message, `toHaveBeenCalled()` and | ||
| `not.toHaveBeenCalled()` should be used when asserting that a mock has or has | ||
| not been called. | ||
|
|
||
| This rule triggers a warning if `toHaveBeenCalledTimes` or `toBeCalledTimes` is | ||
| used to assert that a mock has or has not been called zero times. | ||
|
|
||
| Examples of **incorrect** code for this rule: | ||
|
|
||
| ```js | ||
| expect(method).toHaveBeenCalledTimes(0); | ||
|
|
||
| expect(method).not.toHaveBeenCalledTimes(0); | ||
| ``` | ||
|
|
||
| Examples of **correct** code for this rule: | ||
|
|
||
| ```js | ||
| expect(method).not.toHaveBeenCalled(); | ||
|
|
||
| expect(method).toHaveBeenCalled(); | ||
| ``` | ||
|
|
||
| ## Original Documentation | ||
|
|
||
| - [jest/prefer-to-have-been-called](https://github.com/jest-community/eslint-plugin-jest/blob/main/docs/rules/prefer-to-have-been-called.md) |
91 changes: 91 additions & 0 deletions
91
internal/plugins/jest/rules/prefer_to_have_been_called/prefer_to_have_been_called_test.go
This file contains hidden or 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,91 @@ | ||
| package prefer_to_have_been_called_test | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "github.com/web-infra-dev/rslint/internal/plugins/jest/fixtures" | ||
| "github.com/web-infra-dev/rslint/internal/plugins/jest/rules/prefer_to_have_been_called" | ||
| "github.com/web-infra-dev/rslint/internal/rule_tester" | ||
| ) | ||
|
|
||
| func TestPreferToHaveBeenCalledRule(t *testing.T) { | ||
| rule_tester.RunRuleTester( | ||
| fixtures.GetRootDir(), | ||
| "tsconfig.json", | ||
| t, | ||
| &prefer_to_have_been_called.PreferToHaveBeenCalledRule, | ||
| []rule_tester.ValidTestCase{ | ||
| {Code: `expect(method.mock.calls).toHaveLength;`}, | ||
| {Code: `expect(method.mock.calls).toHaveLength(0);`}, | ||
| {Code: `expect(method).toHaveBeenCalledTimes(1)`}, | ||
| {Code: `expect(method).not.toHaveBeenCalledTimes(x)`}, | ||
| {Code: `expect(method).not.toHaveBeenCalledTimes(1)`}, | ||
| {Code: `expect(method).not.toHaveBeenCalledTimes(...x)`}, | ||
| {Code: `expect(a);`}, | ||
| {Code: `expect(method).not.resolves.toHaveBeenCalledTimes(0);`}, | ||
| {Code: `expect(method).toBeCalledTimes(0!);`}, | ||
| {Code: `expect(method).toBeCalledTimes(0 satisfies number);`}, | ||
| {Code: `expect(method).toBe([])`}, | ||
| {Code: `expect(fn.mock.calls).toEqual([])`}, | ||
| {Code: `expect(fn.mock.calls).toContain(1, 2, 3)`}, | ||
| }, | ||
| []rule_tester.InvalidTestCase{ | ||
| { | ||
| Code: `expect(method).toBeCalledTimes(0);`, | ||
| Output: []string{`expect(method).not.toHaveBeenCalled();`}, | ||
| Errors: []rule_tester.InvalidTestCaseError{ | ||
| {MessageId: "preferMatcher", Line: 1, Column: 16}, | ||
| }, | ||
| }, | ||
| { | ||
| Code: `expect(method).not.toBeCalledTimes(0);`, | ||
| Output: []string{`expect(method).toHaveBeenCalled();`}, | ||
| Errors: []rule_tester.InvalidTestCaseError{ | ||
| {MessageId: "preferMatcher", Line: 1, Column: 20}, | ||
| }, | ||
| }, | ||
| { | ||
| Code: `expect(method).toHaveBeenCalledTimes(0);`, | ||
| Output: []string{`expect(method).not.toHaveBeenCalled();`}, | ||
| Errors: []rule_tester.InvalidTestCaseError{ | ||
| {MessageId: "preferMatcher", Line: 1, Column: 16}, | ||
| }, | ||
| }, | ||
| { | ||
| Code: `expect(method).not.toHaveBeenCalledTimes(0);`, | ||
| Output: []string{`expect(method).toHaveBeenCalled();`}, | ||
| Errors: []rule_tester.InvalidTestCaseError{ | ||
| {MessageId: "preferMatcher", Line: 1, Column: 20}, | ||
| }, | ||
| }, | ||
| { | ||
| Code: `expect(method).not.toHaveBeenCalledTimes(0, 1, 2);`, | ||
| Output: []string{`expect(method).toHaveBeenCalled();`}, | ||
| Errors: []rule_tester.InvalidTestCaseError{ | ||
| {MessageId: "preferMatcher", Line: 1, Column: 20}, | ||
| }, | ||
| }, | ||
| { | ||
| Code: `expect(method).resolves.toHaveBeenCalledTimes(0);`, | ||
| Output: []string{`expect(method).resolves.not.toHaveBeenCalled();`}, | ||
| Errors: []rule_tester.InvalidTestCaseError{ | ||
| {MessageId: "preferMatcher", Line: 1, Column: 25}, | ||
| }, | ||
| }, | ||
| { | ||
| Code: `expect(method).rejects.not.toHaveBeenCalledTimes(0);`, | ||
| Output: []string{`expect(method).rejects.toHaveBeenCalled();`}, | ||
| Errors: []rule_tester.InvalidTestCaseError{ | ||
| {MessageId: "preferMatcher", Line: 1, Column: 28}, | ||
| }, | ||
| }, | ||
| { | ||
| Code: `expect(method).toBeCalledTimes(0 as number);`, | ||
| Output: []string{`expect(method).not.toHaveBeenCalled();`}, | ||
| Errors: []rule_tester.InvalidTestCaseError{ | ||
| {MessageId: "preferMatcher", Line: 1, Column: 16}, | ||
| }, | ||
| }, | ||
| }, | ||
| ) | ||
| } |
This file contains hidden or 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
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The current implementation uses two separate fixes to replace the matcher name and clear the arguments. This can be simplified into a single fix that replaces the entire range from the receiver's end to the end of the call expression. This approach is more robust as it correctly handles potential edge cases like trailing commas or comments within the parentheses, ensuring exact alignment with ESLint's semantics for this rule.
References