Skip to content

Commit 58fa568

Browse files
unknowngndelia
unknown
authored andcommitted
fix(prefer-screen-queries): false positives when using within method
1 parent 4d85337 commit 58fa568

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

docs/rules/prefer-screen-queries.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ import { screen } from '@testing-library/any-framework';
2323

2424
render(<Component />);
2525
screen.getByText('foo');
26+
27+
// using after within clause
28+
within(screen.getByTestId('section')).getByText('foo');
2629
```
2730

2831
## Further Reading

lib/rules/prefer-screen-queries.js

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,23 @@ module.exports = {
3434

3535
return {
3636
[`CallExpression > Identifier[name=/^${ALL_QUERIES_COMBINATIONS_REGEXP}$/]`]: reportInvalidUsage,
37-
[`MemberExpression[object.name!="screen"] > Identifier[name=/^${ALL_QUERIES_COMBINATIONS_REGEXP}$/]`]: reportInvalidUsage,
37+
[`MemberExpression > Identifier[name=/^${ALL_QUERIES_COMBINATIONS_REGEXP}$/]`](
38+
node
39+
) {
40+
if (
41+
node.parent.object.type === 'CallExpression' &&
42+
node.parent.object.callee.name !== 'within'
43+
) {
44+
reportInvalidUsage(node);
45+
return;
46+
}
47+
if (
48+
node.parent.object.type === 'Identifier' &&
49+
node.parent.object.name !== 'screen'
50+
) {
51+
reportInvalidUsage(node);
52+
}
53+
},
3854
};
3955
},
4056
};

tests/lib/rules/prefer-screen-queries.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@ ruleTester.run('prefer-screen-queries', rule, {
2020
{
2121
code: `component.otherFunctionShouldNotThrow()`,
2222
},
23+
...ALL_QUERIES_COMBINATIONS.map(queryMethod => ({
24+
code: `within(component).${queryMethod}()`,
25+
})),
26+
...ALL_QUERIES_COMBINATIONS.map(queryMethod => ({
27+
code: `within(screen.${queryMethod}()).${queryMethod}()`,
28+
})),
2329
],
2430

2531
invalid: [

0 commit comments

Comments
 (0)