Skip to content

feat(prefer-find-by): add fixer for waitFor wrapping findBy queries #1013

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
merged 6 commits into from
May 30, 2025
Merged
Show file tree
Hide file tree
Changes from 2 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
83 changes: 76 additions & 7 deletions lib/rules/prefer-find-by.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@

import { createTestingLibraryRule } from '../create-testing-library-rule';
import {
getDeepestIdentifierNode,
isArrowFunctionExpression,
isBlockStatement,
isCallExpression,
isMemberExpression,
isObjectExpression,
isObjectPattern,
isProperty,
isVariableDeclaration,
} from '../node-utils';
import { getScope, getSourceCode } from '../utils';

Expand All @@ -21,6 +24,10 @@
return queryMethod.includes('All') ? 'findAllBy' : 'findBy';
}

function isFindByQuery(name: string): boolean {
return /^find(All)?By/.test(name);
}

function findRenderDefinitionDeclaration(
scope: TSESLint.Scope.Scope | null,
query: string
Expand Down Expand Up @@ -329,20 +336,82 @@
}

return {
'AwaitExpression > CallExpression'(node: TSESTree.CallExpression) {
'AwaitExpression > CallExpression'(
node: TSESTree.CallExpression & { parent: TSESTree.AwaitExpression }
) {
if (
!ASTUtils.isIdentifier(node.callee) ||
!helpers.isAsyncUtil(node.callee, ['waitFor'])
) {
return;
}
// ensure the only argument is an arrow function expression - if the arrow function is a block
// we skip it
// ensure the only argument is an arrow function expression
const argument = node.arguments[0];
if (
!isArrowFunctionExpression(argument) ||
!isCallExpression(argument.body)
) {

if (!isArrowFunctionExpression(argument)) {
return;
}

if (isBlockStatement(argument.body) && argument.async) {
const { body } = argument.body;
const declarations = body
.filter(isVariableDeclaration)
?.flatMap((declaration) => declaration.declarations);

const findByDeclarator = declarations.find((declaration) => {
if (
!ASTUtils.isAwaitExpression(declaration.init) ||
!isCallExpression(declaration.init.argument)
) {
return false;

Check warning on line 366 in lib/rules/prefer-find-by.ts

View check run for this annotation

Codecov / codecov/patch

lib/rules/prefer-find-by.ts#L366

Added line #L366 was not covered by tests
}

const { callee } = declaration.init.argument;

const name = getDeepestIdentifierNode(callee)?.name;
return name ? isFindByQuery(name) : false;
});

const init = ASTUtils.isAwaitExpression(findByDeclarator?.init)
? findByDeclarator.init?.argument
: null;

Check warning on line 377 in lib/rules/prefer-find-by.ts

View check run for this annotation

Codecov / codecov/patch

lib/rules/prefer-find-by.ts#L377

Added line #L377 was not covered by tests

if (!isCallExpression(init)) {
return;

Check warning on line 380 in lib/rules/prefer-find-by.ts

View check run for this annotation

Codecov / codecov/patch

lib/rules/prefer-find-by.ts#L380

Added line #L380 was not covered by tests
}
const queryIdentifier = getDeepestIdentifierNode(init.callee);

if (!queryIdentifier || !helpers.isAsyncQuery(queryIdentifier)) {
return;

Check warning on line 385 in lib/rules/prefer-find-by.ts

View check run for this annotation

Codecov / codecov/patch

lib/rules/prefer-find-by.ts#L385

Added line #L385 was not covered by tests
}

const fullQueryMethod = queryIdentifier.name;
const queryMethod = fullQueryMethod.split('By')[1];
const queryVariant = getFindByQueryVariant(fullQueryMethod);

reportInvalidUsage(node, {
queryMethod,
queryVariant,
prevQuery: fullQueryMethod,
fix(fixer) {
const { parent: expressionStatement } = node.parent;
const bodyText = sourceCode
.getText(argument.body)
.slice(1, -1)
.trim();
const { line, column } = expressionStatement.loc.start;
const indent = sourceCode.getLines()[line - 1].slice(0, column);
const newText = bodyText
.split('\n')
.map((line) => line.trim())
.join(`\n${indent}`);
return fixer.replaceText(expressionStatement, newText);
},
});
return;
}

if (!isCallExpression(argument.body)) {
return;
}

Expand Down
29 changes: 29 additions & 0 deletions tests/lib/rules/prefer-find-by.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,35 @@ ruleTester.run(RULE_NAME, rule, {
const button = await screen.${buildFindByMethod(
queryMethod
)}('Count is: 0', { timeout: 100, interval: 200 })
`,
})),
...ASYNC_QUERIES_COMBINATIONS.map((queryMethod) => ({
code: `
import {waitFor} from '${testingFramework}';
it('tests', async () => {
await waitFor(async () => {
const button = await screen.${queryMethod}("button", { name: "Submit" })
expect(button).toBeInTheDocument()
})
})
`,
errors: [
{
messageId: 'preferFindBy',
data: {
queryVariant: getFindByQueryVariant(queryMethod),
queryMethod: queryMethod.split('By')[1],
prevQuery: queryMethod,
waitForMethodName: 'waitFor',
},
},
],
output: `
import {waitFor} from '${testingFramework}';
it('tests', async () => {
const button = await screen.${queryMethod}("button", { name: "Submit" })
expect(button).toBeInTheDocument()
})
`,
})),
]),
Expand Down