Skip to content

fix(prefer-screen-queries): false positives when using within method #119

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
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions docs/rules/prefer-screen-queries.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,37 @@ Examples of **incorrect** code for this rule:
const { getByText } = render(<Component />);
getByText('foo');

// calling a query from a variable returned from a `render` method
const utils = render(<Component />);
utils.getByText('foo');

// using after render
render(<Component />).getByText('foo');

// calling a query from a custom `render` method that returns an array
const [getByText] = myCustomRender(<Component />);
getByText('foo');
```

Examples of **correct** code for this rule:

```js
import { screen } from '@testing-library/any-framework';

// calling a query from the `screen` object
render(<Component />);
screen.getByText('foo');

// using after within clause
within(screen.getByTestId('section')).getByText('foo');

// calling a query method returned from a within call
const { getByText } = within(screen.getByText('foo'));
getByText('foo');

// calling a method directly from a variable created by within
const myWithinVariable = within(screen.getByText('foo'));
myWithinVariable.getByText('foo');
```

## Further Reading
Expand Down
72 changes: 70 additions & 2 deletions lib/rules/prefer-screen-queries.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import { ESLintUtils, TSESTree } from '@typescript-eslint/experimental-utils';
import { getDocsUrl, ALL_QUERIES_COMBINATIONS } from '../utils';
import {
isMemberExpression,
isObjectPattern,
isCallExpression,
isProperty,
isIdentifier,
} from '../node-utils';

export const RULE_NAME = 'prefer-screen-queries';
export type MessageIds = 'preferScreenQueries';
Expand Down Expand Up @@ -36,9 +43,70 @@ export default ESLintUtils.RuleCreator(getDocsUrl)<Options, MessageIds>({
});
}

const queriesRegex = new RegExp(ALL_QUERIES_COMBINATIONS_REGEXP);
const queriesDestructuredInWithinDeclaration: string[] = [];
// use an array as within might be used more than once in a test
const withinDeclaredVariables : string[] = []

return {
[`CallExpression > Identifier[name=/^${ALL_QUERIES_COMBINATIONS_REGEXP}$/]`]: reportInvalidUsage,
[`MemberExpression[object.name!="screen"] > Identifier[name=/^${ALL_QUERIES_COMBINATIONS_REGEXP}$/]`]: reportInvalidUsage,
VariableDeclarator(node) {
const isWithinFunction = isCallExpression(node.init) && isIdentifier(node.init.callee) && node.init.callee.name === 'within';

if (!isWithinFunction) {
return
}

if (isObjectPattern(node.id)) {
// save the destructured query methods
const identifiers = node.id.properties
.filter(property => isProperty(property) && isIdentifier(property.key) && queriesRegex.test(property.key.name))
.map((property: TSESTree.Property) => (property.key as TSESTree.Identifier).name);

queriesDestructuredInWithinDeclaration.push(...identifiers);
return
}

if (isIdentifier(node.id)) {
withinDeclaredVariables.push(node.id.name)
}
},
[`CallExpression > Identifier[name=/^${ALL_QUERIES_COMBINATIONS_REGEXP}$/]`](
node: TSESTree.Identifier
) {
if (
!queriesDestructuredInWithinDeclaration.some(
queryName => queryName === node.name
)
) {
reportInvalidUsage(node);
}
},
[`MemberExpression > Identifier[name=/^${ALL_QUERIES_COMBINATIONS_REGEXP}$/]`](
node: TSESTree.Identifier
) {

function isIdentifierAllowed(name: string) {
return ['screen', ...withinDeclaredVariables].includes(name)
}

if (
isIdentifier(node) &&
isMemberExpression(node.parent) &&
isCallExpression(node.parent.object) &&
isIdentifier(node.parent.object.callee) &&
node.parent.object.callee.name !== 'within'
) {
reportInvalidUsage(node);
return;
}
if (
isMemberExpression(node.parent) &&
isIdentifier(node.parent.object) &&
!isIdentifierAllowed(node.parent.object.name)
) {
reportInvalidUsage(node);
}
},
};
},
});
86 changes: 86 additions & 0 deletions tests/lib/rules/prefer-screen-queries.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,24 @@ ruleTester.run(RULE_NAME, rule, {
{
code: `component.otherFunctionShouldNotThrow()`,
},
...ALL_QUERIES_COMBINATIONS.map(queryMethod => ({
code: `within(component).${queryMethod}()`,
})),
...ALL_QUERIES_COMBINATIONS.map(queryMethod => ({
code: `within(screen.${queryMethod}()).${queryMethod}()`,
})),
...ALL_QUERIES_COMBINATIONS.map(queryMethod => ({
code: `
const { ${queryMethod} } = within(screen.getByText('foo'))
${queryMethod}(baz)
`,
})),
...ALL_QUERIES_COMBINATIONS.map(queryMethod => ({
code: `
const myWithinVariable = within(foo)
myWithinVariable.${queryMethod}('baz')
`,
})),
],

invalid: [
Expand All @@ -30,6 +48,18 @@ ruleTester.run(RULE_NAME, rule, {
],
})),

...ALL_QUERIES_COMBINATIONS.map(queryMethod => ({
code: `render().${queryMethod}()`,
errors: [
{
messageId: 'preferScreenQueries',
data: {
name: queryMethod,
},
},
],
})),

...ALL_QUERIES_COMBINATIONS.map(queryMethod => ({
code: `component.${queryMethod}()`,
errors: [
Expand All @@ -41,5 +71,61 @@ ruleTester.run(RULE_NAME, rule, {
},
],
})),
...ALL_QUERIES_COMBINATIONS.map(queryMethod => ({
code: `
const { ${queryMethod} } = render()
${queryMethod}(baz)
`,
errors: [
{
messageId: 'preferScreenQueries',
data: {
name: queryMethod,
},
},
],
})),
...ALL_QUERIES_COMBINATIONS.map(queryMethod => ({
code: `
const myRenderVariable = render()
myRenderVariable.${queryMethod}(baz)
`,
errors: [
{
messageId: 'preferScreenQueries',
data: {
name: queryMethod,
},
},
],
})),
...ALL_QUERIES_COMBINATIONS.map(queryMethod => ({
code: `
const [myVariable] = render()
myVariable.${queryMethod}(baz)
`,
errors: [
{
messageId: 'preferScreenQueries',
data: {
name: queryMethod,
},
},
],
})),
...ALL_QUERIES_COMBINATIONS.map(queryMethod => ({
code: `
const [myVariable] = within()
myVariable.${queryMethod}(baz)
`,
errors: [
{
messageId: 'preferScreenQueries',
data: {
name: queryMethod,
},
},
],
})),
],
});