Skip to content

Commit

Permalink
fix(no-wait-for-side-effects): false negatives in variables declarati…
Browse files Browse the repository at this point in the history
…ons (#677)

fix: false negatives in variables declarations

Closes #368
  • Loading branch information
sjarva authored Oct 17, 2022
1 parent e2a08f4 commit c3504a7
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
41 changes: 41 additions & 0 deletions lib/rules/no-wait-for-side-effects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,40 @@ export default createTestingLibraryRule<Options, MessageIds>({
return node.expressions.some(isRenderInAssignmentExpression);
}

/**
* Checks if there are side effects in variable declarations.
*
* For example, these variable declarations have side effects:
* const a = userEvent.doubleClick(button);
* const b = fireEvent.click(button);
* const wrapper = render(<Component />);
*
* @param node
* @returns {Boolean} Boolean indicating if variable declarataion has side effects
*/
function isSideEffectInVariableDeclaration(
node: TSESTree.VariableDeclaration
): boolean {
return node.declarations.some((declaration) => {
if (isCallExpression(declaration.init)) {
const test = getPropertyIdentifierNode(declaration.init);

if (!test) {
return false;
}

return (
helpers.isFireEventUtil(test) ||
helpers.isUserEventUtil(test) ||
helpers.isRenderUtil(test)
);
}
return false;
});

return false;
}

function getSideEffectNodes(
body: TSESTree.Node[]
): TSESTree.ExpressionStatement[] {
Expand All @@ -135,6 +169,13 @@ export default createTestingLibraryRule<Options, MessageIds>({
return true;
}

if (
isVariableDeclaration(node) &&
isSideEffectInVariableDeclaration(node)
) {
return true;
}

const expressionIdentifier = getPropertyIdentifierNode(node);

if (!expressionIdentifier) {
Expand Down
20 changes: 20 additions & 0 deletions tests/lib/rules/no-wait-for-side-effects.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -795,5 +795,25 @@ ruleTester.run(RULE_NAME, rule, {
{ line: 12, column: 13, messageId: 'noSideEffectsWaitFor' },
],
},
// side effects (userEvent, fireEvent or render) in variable declarations
...SUPPORTED_TESTING_FRAMEWORKS.flatMap((testingFramework) => [
{
// Issue #368, https://github.com/testing-library/eslint-plugin-testing-library/issues/368
code: `
import { waitFor } from '${testingFramework}';
import userEvent from '@testing-library/user-event'
await waitFor(() => {
const a = userEvent.click(button);
const b = fireEvent.click(button);
const wrapper = render(<App />);
})
`,
errors: [
{ line: 5, column: 11, messageId: 'noSideEffectsWaitFor' },
{ line: 6, column: 11, messageId: 'noSideEffectsWaitFor' },
{ line: 7, column: 11, messageId: 'noSideEffectsWaitFor' },
],
} as const,
]),
],
});

0 comments on commit c3504a7

Please sign in to comment.