Skip to content

feat: add rule no-multiple-assertions-wait-for #189

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 16 commits into from
Jun 30, 2020
Merged
Show file tree
Hide file tree
Changes from 7 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
43 changes: 43 additions & 0 deletions docs/rules/no-multiple-assertions-wait-for.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Multiple assertions inside `waitFor` are not preferred (no-multiple-assertions-wait-for)

## Rule Details

This rule aims to ensure the correct usage of `expect` inside `waitFor`, in the way that they're intended to be used.
When using multiples assertions inside `waitFor`, if one fails, you have to wait for timeout before see it failing.
Putting one assertion, you can both wait for the UI to settle to the state you want to assert on,
and also fail faster if one of the assertions do end up failing

Example of **incorrect** code for this rule:

```js
const foo = async () => {
await waitFor(() => {
expect(a).toEqual('a');
expect(b).toEqual('b');
});
};
```

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

```js
const foo = async () => {
await waitFor(() => expect(a).toEqual('a'));

// this rule only looks for expect
await waitFor(() => {
fireEvent.keyDown(input, { key: 'ArrowDown' });
expect(b).toEqual('b');
});

// or
await waitFor(() => {
console.log('testing-library');
expect(b).toEqual('b');
});
};
```

## Further Reading

- [about `waitFor`](https://testing-library.com/docs/dom-testing-library/api-async#waitfor)
2 changes: 2 additions & 0 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import preferExplicitAssert from './rules/prefer-explicit-assert';
import preferPresenceQueries from './rules/prefer-presence-queries';
import preferScreenQueries from './rules/prefer-screen-queries';
import preferWaitFor from './rules/prefer-wait-for';
import noMultipleAssertionsWaitFor from './rules/no-multiple-assertions-wait-for'
import preferFindBy from './rules/prefer-find-by';

const rules = {
Expand All @@ -25,6 +26,7 @@ const rules = {
'no-debug': noDebug,
'no-dom-import': noDomImport,
'no-manual-cleanup': noManualCleanup,
'no-multiple-assertions-wait-for': noMultipleAssertionsWaitFor,
'no-promise-in-fire-event': noPromiseInFireEvent,
'no-wait-for-empty-callback': noWaitForEmptyCallback,
'prefer-explicit-assert': preferExplicitAssert,
Expand Down
17 changes: 17 additions & 0 deletions lib/node-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,23 @@ export function findClosestCallNode(
}
}

export function findClosestCalleName(
node: TSESTree.Node
): string {
if (!node.parent) {
return '';
}

if (
isCallExpression(node) &&
isIdentifier(node.callee)
) {
return node.callee.name;
} else {
return findClosestCalleName(node.parent);
}
}

export function hasThenProperty(node: TSESTree.Node) {
return (
isMemberExpression(node) &&
Expand Down
67 changes: 67 additions & 0 deletions lib/rules/no-multiple-assertions-wait-for.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { ESLintUtils, TSESTree } from '@typescript-eslint/experimental-utils'
import { getDocsUrl } from '../utils'
import { isBlockStatement, findClosestCalleName, isMemberExpression, isCallExpression, isIdentifier } from '../node-utils'

export const RULE_NAME = 'no-multiple-expect-wait-for';

const WAIT_EXPRESSION_QUERY =
'CallExpression[callee.name=/^(waitFor)$/]';

export type MessageIds = 'noMultipleAssertionWaitFor';
type Options = [];

export default ESLintUtils.RuleCreator(getDocsUrl)<Options, MessageIds>({
name: RULE_NAME,
meta: {
type: 'suggestion',
docs: {
description:
"It's preferred to avoid multiple assertions in `waitFor`",
category: 'Best Practices',
recommended: false,
},
messages: {
noMultipleAssertionWaitFor: 'Avoid use multiple assertions to `{{ methodName }}`',
},
fixable: null,
schema: [],
},
defaultOptions: [],
create: function(context) {
function reporttMultipleAssertion(
node: TSESTree.BlockStatement
) {
const hasMultipleExpects = (body: Array<TSESTree.Node>): boolean =>
body.every((node: TSESTree.ExpressionStatement) => {
if (
isCallExpression(node?.expression) &&
isMemberExpression(node?.expression?.callee) &&
isCallExpression(node?.expression?.callee?.object)
) {
const object: TSESTree.CallExpression = node?.expression?.callee?.object
const expressionName: string = (object?.callee as TSESTree.Identifier)?.name
return expressionName === 'expect'
} else {
return false
}
})

if (isBlockStatement(node) && node.body.length > 1 && hasMultipleExpects(node.body)) {
const methodName: string = findClosestCalleName(node)
context.report({
node,
loc: node.loc.start,
messageId: 'noMultipleAssertionWaitFor',
data: {
methodName,
},
});
}
}

return {
[`${WAIT_EXPRESSION_QUERY} > ArrowFunctionExpression > BlockStatement`]: reporttMultipleAssertion,
[`${WAIT_EXPRESSION_QUERY} > FunctionExpression > BlockStatement`]: reporttMultipleAssertion,
};
}
})
46 changes: 46 additions & 0 deletions tests/lib/rules/no-multiple-assertions-wait-for.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { createRuleTester } from '../test-utils';
import rule, { RULE_NAME } from '../../../lib/rules/no-multiple-assertions-wait-for';

const ruleTester = createRuleTester({
ecmaFeatures: {
jsx: true,
},
});

ruleTester.run(RULE_NAME, rule, {
valid: [
{
code: `
await waitFor(() => expect(a).toEqual('a'))
`,
},
// this needs to be check by other rule
{
code: `
await waitFor(() => {
fireEvent.keyDown(input, {key: 'ArrowDown'})
expect(b).toEqual('b')
})
`,
},
{
code: `
await waitFor(() => {
console.log('testing-library')
expect(b).toEqual('b')
})
`,
}
],
invalid: [
{
code: `
await waitFor(() => {
expect(a).toEqual('a')
expect(b).toEqual('b')
})
`,
errors: [{ messageId: 'noMultipleAssertionWaitFor' }]
}
]
})