-
Notifications
You must be signed in to change notification settings - Fork 150
feat: add prefer-query-matchers
rule
#750
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
Merged
Belco90
merged 9 commits into
testing-library:main
from
testdouble:pr/prefer-query-matchers
May 10, 2023
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
8606e24
feat: add prefer-query-matchers rule
CodingItWrong 1ba34cf
test: cover prefer-query-matchers with test
CodingItWrong 99e0d2c
feat: set default options to no configured entries to check for
CodingItWrong b212af4
docs: add query doc and supported rules table entry
CodingItWrong d08851d
style: prettify rule file
CodingItWrong 625c438
fix: do not include prefer-query-matchers by default
CodingItWrong 429b90c
fix: failing test
CodingItWrong d0b9e6c
fix: make generated tests more realistic AST
CodingItWrong 8073bf9
fix: comment out test names
CodingItWrong 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,85 @@ | ||
# Ensure the configured `get*`/`query*` query is used with the corresponding matchers (`testing-library/prefer-query-matchers`) | ||
|
||
<!-- end auto-generated rule header --> | ||
|
||
The (DOM) Testing Library allows to query DOM elements using different types of queries such as `get*` and `query*`. Using `get*` throws an error in case the element is not found, while `query*` returns null instead of throwing (or empty array for `queryAllBy*` ones). | ||
|
||
It may be helpful to ensure that either `get*` or `query*` are always used for a given matcher. For example, `.toBeVisible()` and the negation `.not.toBeVisible()` both assume that an element exists in the DOM and will error if not. Using `get*` with `.toBeVisible()` ensures that if the element is not found the error thrown will offer better info than with `query*`. | ||
|
||
## Rule details | ||
|
||
This rule must be configured with a list of `validEntries`: for a given matcher, is `get*` or `query*` required. | ||
|
||
Assuming the following configuration: | ||
|
||
```json | ||
{ | ||
"testing-library/prefer-query-matchers": [ | ||
2, | ||
{ | ||
"validEntries": [{ "matcher": "toBeVisible", "query": "get" }] | ||
} | ||
] | ||
} | ||
``` | ||
|
||
Examples of **incorrect** code for this rule with the above configuration: | ||
|
||
```js | ||
test('some test', () => { | ||
render(<App />); | ||
|
||
// use configured matcher with the disallowed `query*` | ||
expect(screen.queryByText('button')).toBeVisible(); | ||
expect(screen.queryByText('button')).not.toBeVisible(); | ||
expect(screen.queryAllByText('button')[0]).toBeVisible(); | ||
expect(screen.queryAllByText('button')[0]).not.toBeVisible(); | ||
}); | ||
``` | ||
|
||
Examples of **correct** code for this rule: | ||
|
||
```js | ||
test('some test', async () => { | ||
render(<App />); | ||
// use configured matcher with the allowed `get*` | ||
expect(screen.getByText('button')).toBeVisible(); | ||
expect(screen.getByText('button')).not.toBeVisible(); | ||
expect(screen.getAllByText('button')[0]).toBeVisible(); | ||
expect(screen.getAllByText('button')[0]).not.toBeVisible(); | ||
|
||
// use an unconfigured matcher with either `get* or `query* | ||
expect(screen.getByText('button')).toBeEnabled(); | ||
expect(screen.getAllByText('checkbox')[0]).not.toBeChecked(); | ||
expect(screen.queryByText('button')).toHaveFocus(); | ||
expect(screen.queryAllByText('button')[0]).not.toMatchMyCustomMatcher(); | ||
|
||
// `findBy*` queries are out of the scope for this rule | ||
const button = await screen.findByText('submit'); | ||
expect(button).toBeVisible(); | ||
}); | ||
``` | ||
|
||
## Options | ||
|
||
| Option | Required | Default | Details | | ||
| -------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | ||
| `validEntries` | No | `[]` | A list of objects with a `matcher` property (the name of any matcher, such as "toBeVisible") and a `query` property (either "get" or "query"). Indicates whether `get*` or `query*` are allowed with this matcher. | | ||
|
||
## Example | ||
|
||
```json | ||
{ | ||
"testing-library/prefer-query-matchers": [ | ||
2, | ||
{ | ||
"validEntries": [{ "matcher": "toBeVisible", "query": "get" }] | ||
} | ||
] | ||
} | ||
``` | ||
|
||
## Further Reading | ||
|
||
- [Testing Library queries cheatsheet](https://testing-library.com/docs/dom-testing-library/cheatsheet#queries) | ||
- [jest-dom note about using `getBy` within assertions](https://testing-library.com/docs/ecosystem-jest-dom) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
import { TSESTree } from '@typescript-eslint/utils'; | ||
|
||
import { createTestingLibraryRule } from '../create-testing-library-rule'; | ||
import { findClosestCallNode, isMemberExpression } from '../node-utils'; | ||
|
||
export const RULE_NAME = 'prefer-query-matchers'; | ||
export type MessageIds = 'wrongQueryForMatcher'; | ||
export type Options = [ | ||
{ | ||
validEntries: { | ||
query: 'get' | 'query'; | ||
matcher: string; | ||
}[]; | ||
} | ||
]; | ||
|
||
export default createTestingLibraryRule<Options, MessageIds>({ | ||
name: RULE_NAME, | ||
meta: { | ||
docs: { | ||
description: | ||
'Ensure the configured `get*`/`query*` query is used with the corresponding matchers', | ||
recommendedConfig: { | ||
dom: false, | ||
angular: false, | ||
react: false, | ||
vue: false, | ||
marko: false, | ||
}, | ||
}, | ||
messages: { | ||
wrongQueryForMatcher: 'Use `{{ query }}By*` queries for {{ matcher }}', | ||
}, | ||
schema: [ | ||
{ | ||
type: 'object', | ||
additionalProperties: false, | ||
properties: { | ||
validEntries: { | ||
type: 'array', | ||
items: { | ||
type: 'object', | ||
properties: { | ||
query: { | ||
type: 'string', | ||
enum: ['get', 'query'], | ||
}, | ||
matcher: { | ||
type: 'string', | ||
}, | ||
}, | ||
}, | ||
}, | ||
}, | ||
}, | ||
], | ||
type: 'suggestion', | ||
}, | ||
defaultOptions: [ | ||
{ | ||
validEntries: [], | ||
}, | ||
], | ||
|
||
create(context, [{ validEntries }], helpers) { | ||
return { | ||
'CallExpression Identifier'(node: TSESTree.Identifier) { | ||
const expectCallNode = findClosestCallNode(node, 'expect'); | ||
|
||
if (!expectCallNode || !isMemberExpression(expectCallNode.parent)) { | ||
return; | ||
} | ||
|
||
// Sync queries (getBy and queryBy) and corresponding ones | ||
// are supported. If none found, stop the rule. | ||
if (!helpers.isSyncQuery(node)) { | ||
return; | ||
} | ||
|
||
const isGetBy = helpers.isGetQueryVariant(node); | ||
const expectStatement = expectCallNode.parent; | ||
for (const entry of validEntries) { | ||
const { query, matcher } = entry; | ||
const isMatchingAssertForThisEntry = helpers.isMatchingAssert( | ||
expectStatement, | ||
matcher | ||
); | ||
|
||
if (!isMatchingAssertForThisEntry) { | ||
continue; | ||
} | ||
|
||
const actualQuery = isGetBy ? 'get' : 'query'; | ||
if (query !== actualQuery) { | ||
context.report({ | ||
node, | ||
messageId: 'wrongQueryForMatcher', | ||
data: { query, matcher }, | ||
}); | ||
} | ||
} | ||
}, | ||
}; | ||
}, | ||
}); |
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.
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.
Uh oh!
There was an error while loading. Please reload this page.