Skip to content

Commit 31516ad

Browse files
feat: add prefer-query-matchers rule (#750)
* feat: add prefer-query-matchers rule Co-authored-by: Dale Karp <[email protected]> * test: cover prefer-query-matchers with test Co-authored-by: Dale Karp <[email protected]> * feat: set default options to no configured entries to check for Co-authored-by: Dale Karp <[email protected]> * docs: add query doc and supported rules table entry * style: prettify rule file * fix: do not include prefer-query-matchers by default * fix: failing test * fix: make generated tests more realistic AST * fix: comment out test names --------- Co-authored-by: Dale Karp <[email protected]>
1 parent 3f2f4f8 commit 31516ad

7 files changed

+609
-1
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,7 @@ module.exports = {
228228
| [prefer-find-by](docs/rules/prefer-find-by.md) | Suggest using `find(All)By*` query instead of `waitFor` + `get(All)By*` to wait for elements | ![badge-angular][] ![badge-dom][] ![badge-marko][] ![badge-react][] ![badge-vue][] | 🔧 |
229229
| [prefer-presence-queries](docs/rules/prefer-presence-queries.md) | Ensure appropriate `get*`/`query*` queries are used with their respective matchers | ![badge-angular][] ![badge-dom][] ![badge-marko][] ![badge-react][] ![badge-vue][] | |
230230
| [prefer-query-by-disappearance](docs/rules/prefer-query-by-disappearance.md) | Suggest using `queryBy*` queries when waiting for disappearance | ![badge-angular][] ![badge-dom][] ![badge-marko][] ![badge-react][] ![badge-vue][] | |
231+
| [prefer-query-matchers](docs/rules/prefer-query-matchers.md) | Ensure the configured `get*`/`query*` query is used with the corresponding matchers | | |
231232
| [prefer-screen-queries](docs/rules/prefer-screen-queries.md) | Suggest using `screen` while querying | ![badge-angular][] ![badge-dom][] ![badge-marko][] ![badge-react][] ![badge-vue][] | |
232233
| [prefer-user-event](docs/rules/prefer-user-event.md) | Suggest using `userEvent` over `fireEvent` for simulating user interactions | | |
233234
| [prefer-wait-for](docs/rules/prefer-wait-for.md) | Use `waitFor` instead of deprecated wait methods | | 🔧 |

docs/rules/prefer-presence-queries.md

+1
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ Examples of **correct** code for this rule:
4343
```js
4444
test('some test', async () => {
4545
render(<App />);
46+
4647
// check element is present with `getBy*`
4748
expect(screen.getByText('button')).toBeInTheDocument();
4849
expect(screen.getAllByText('button')[9]).toBeTruthy();

docs/rules/prefer-query-matchers.md

+85
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# Ensure the configured `get*`/`query*` query is used with the corresponding matchers (`testing-library/prefer-query-matchers`)
2+
3+
<!-- end auto-generated rule header -->
4+
5+
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).
6+
7+
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*`.
8+
9+
## Rule details
10+
11+
This rule must be configured with a list of `validEntries`: for a given matcher, is `get*` or `query*` required.
12+
13+
Assuming the following configuration:
14+
15+
```json
16+
{
17+
"testing-library/prefer-query-matchers": [
18+
2,
19+
{
20+
"validEntries": [{ "matcher": "toBeVisible", "query": "get" }]
21+
}
22+
]
23+
}
24+
```
25+
26+
Examples of **incorrect** code for this rule with the above configuration:
27+
28+
```js
29+
test('some test', () => {
30+
render(<App />);
31+
32+
// use configured matcher with the disallowed `query*`
33+
expect(screen.queryByText('button')).toBeVisible();
34+
expect(screen.queryByText('button')).not.toBeVisible();
35+
expect(screen.queryAllByText('button')[0]).toBeVisible();
36+
expect(screen.queryAllByText('button')[0]).not.toBeVisible();
37+
});
38+
```
39+
40+
Examples of **correct** code for this rule:
41+
42+
```js
43+
test('some test', async () => {
44+
render(<App />);
45+
// use configured matcher with the allowed `get*`
46+
expect(screen.getByText('button')).toBeVisible();
47+
expect(screen.getByText('button')).not.toBeVisible();
48+
expect(screen.getAllByText('button')[0]).toBeVisible();
49+
expect(screen.getAllByText('button')[0]).not.toBeVisible();
50+
51+
// use an unconfigured matcher with either `get* or `query*
52+
expect(screen.getByText('button')).toBeEnabled();
53+
expect(screen.getAllByText('checkbox')[0]).not.toBeChecked();
54+
expect(screen.queryByText('button')).toHaveFocus();
55+
expect(screen.queryAllByText('button')[0]).not.toMatchMyCustomMatcher();
56+
57+
// `findBy*` queries are out of the scope for this rule
58+
const button = await screen.findByText('submit');
59+
expect(button).toBeVisible();
60+
});
61+
```
62+
63+
## Options
64+
65+
| Option | Required | Default | Details |
66+
| -------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
67+
| `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. |
68+
69+
## Example
70+
71+
```json
72+
{
73+
"testing-library/prefer-query-matchers": [
74+
2,
75+
{
76+
"validEntries": [{ "matcher": "toBeVisible", "query": "get" }]
77+
}
78+
]
79+
}
80+
```
81+
82+
## Further Reading
83+
84+
- [Testing Library queries cheatsheet](https://testing-library.com/docs/dom-testing-library/cheatsheet#queries)
85+
- [jest-dom note about using `getBy` within assertions](https://testing-library.com/docs/ecosystem-jest-dom)

lib/create-testing-library-rule/detect-testing-library-utils.ts

+16
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,10 @@ type IsDebugUtilFn = (
8585
validNames?: ReadonlyArray<(typeof DEBUG_UTILS)[number]>
8686
) => boolean;
8787
type IsPresenceAssertFn = (node: TSESTree.MemberExpression) => boolean;
88+
type IsMatchingAssertFn = (
89+
node: TSESTree.MemberExpression,
90+
matcherName: string
91+
) => boolean;
8892
type IsAbsenceAssertFn = (node: TSESTree.MemberExpression) => boolean;
8993
type CanReportErrorsFn = () => boolean;
9094
type FindImportedTestingLibraryUtilSpecifierFn = (
@@ -122,6 +126,7 @@ export interface DetectionHelpers {
122126
isActUtil: (node: TSESTree.Identifier) => boolean;
123127
isPresenceAssert: IsPresenceAssertFn;
124128
isAbsenceAssert: IsAbsenceAssertFn;
129+
isMatchingAssert: IsMatchingAssertFn;
125130
canReportErrors: CanReportErrorsFn;
126131
findImportedTestingLibraryUtilSpecifier: FindImportedTestingLibraryUtilSpecifierFn;
127132
isNodeComingFromTestingLibrary: IsNodeComingFromTestingLibraryFn;
@@ -819,6 +824,16 @@ export function detectTestingLibraryUtils<
819824
: ABSENCE_MATCHERS.includes(matcher);
820825
};
821826

827+
const isMatchingAssert: IsMatchingAssertFn = (node, matcherName) => {
828+
const { matcher } = getAssertNodeInfo(node);
829+
830+
if (!matcher) {
831+
return false;
832+
}
833+
834+
return matcher === matcherName;
835+
};
836+
822837
/**
823838
* Finds the import util specifier related to Testing Library for a given name.
824839
*/
@@ -977,6 +992,7 @@ export function detectTestingLibraryUtils<
977992
isDebugUtil,
978993
isActUtil,
979994
isPresenceAssert,
995+
isMatchingAssert,
980996
isAbsenceAssert,
981997
canReportErrors,
982998
findImportedTestingLibraryUtilSpecifier,

lib/rules/prefer-query-matchers.ts

+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
import { TSESTree } from '@typescript-eslint/utils';
2+
3+
import { createTestingLibraryRule } from '../create-testing-library-rule';
4+
import { findClosestCallNode, isMemberExpression } from '../node-utils';
5+
6+
export const RULE_NAME = 'prefer-query-matchers';
7+
export type MessageIds = 'wrongQueryForMatcher';
8+
export type Options = [
9+
{
10+
validEntries: {
11+
query: 'get' | 'query';
12+
matcher: string;
13+
}[];
14+
}
15+
];
16+
17+
export default createTestingLibraryRule<Options, MessageIds>({
18+
name: RULE_NAME,
19+
meta: {
20+
docs: {
21+
description:
22+
'Ensure the configured `get*`/`query*` query is used with the corresponding matchers',
23+
recommendedConfig: {
24+
dom: false,
25+
angular: false,
26+
react: false,
27+
vue: false,
28+
marko: false,
29+
},
30+
},
31+
messages: {
32+
wrongQueryForMatcher: 'Use `{{ query }}By*` queries for {{ matcher }}',
33+
},
34+
schema: [
35+
{
36+
type: 'object',
37+
additionalProperties: false,
38+
properties: {
39+
validEntries: {
40+
type: 'array',
41+
items: {
42+
type: 'object',
43+
properties: {
44+
query: {
45+
type: 'string',
46+
enum: ['get', 'query'],
47+
},
48+
matcher: {
49+
type: 'string',
50+
},
51+
},
52+
},
53+
},
54+
},
55+
},
56+
],
57+
type: 'suggestion',
58+
},
59+
defaultOptions: [
60+
{
61+
validEntries: [],
62+
},
63+
],
64+
65+
create(context, [{ validEntries }], helpers) {
66+
return {
67+
'CallExpression Identifier'(node: TSESTree.Identifier) {
68+
const expectCallNode = findClosestCallNode(node, 'expect');
69+
70+
if (!expectCallNode || !isMemberExpression(expectCallNode.parent)) {
71+
return;
72+
}
73+
74+
// Sync queries (getBy and queryBy) and corresponding ones
75+
// are supported. If none found, stop the rule.
76+
if (!helpers.isSyncQuery(node)) {
77+
return;
78+
}
79+
80+
const isGetBy = helpers.isGetQueryVariant(node);
81+
const expectStatement = expectCallNode.parent;
82+
for (const entry of validEntries) {
83+
const { query, matcher } = entry;
84+
const isMatchingAssertForThisEntry = helpers.isMatchingAssert(
85+
expectStatement,
86+
matcher
87+
);
88+
89+
if (!isMatchingAssertForThisEntry) {
90+
continue;
91+
}
92+
93+
const actualQuery = isGetBy ? 'get' : 'query';
94+
if (query !== actualQuery) {
95+
context.report({
96+
node,
97+
messageId: 'wrongQueryForMatcher',
98+
data: { query, matcher },
99+
});
100+
}
101+
}
102+
},
103+
};
104+
},
105+
});

tests/index.test.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { resolve } from 'path';
33

44
import plugin from '../lib';
55

6-
const numberOfRules = 27;
6+
const numberOfRules = 28;
77
const ruleNames = Object.keys(plugin.rules);
88

99
// eslint-disable-next-line jest/expect-expect

0 commit comments

Comments
 (0)