|
| 1 | +import { ESLintUtils, TSESTree } from '@typescript-eslint/experimental-utils' |
| 2 | +import { getDocsUrl } from '../utils' |
| 3 | +import { isBlockStatement, findClosestCallNode, isMemberExpression, isCallExpression, isIdentifier } from '../node-utils' |
| 4 | + |
| 5 | +export const RULE_NAME = 'no-multiple-assertions-wait-for'; |
| 6 | + |
| 7 | +const WAIT_EXPRESSION_QUERY = |
| 8 | + 'CallExpression[callee.name=/^(waitFor)$/]'; |
| 9 | + |
| 10 | +export type MessageIds = 'noMultipleAssertionWaitFor'; |
| 11 | +type Options = []; |
| 12 | + |
| 13 | +export default ESLintUtils.RuleCreator(getDocsUrl)<Options, MessageIds>({ |
| 14 | + name: RULE_NAME, |
| 15 | + meta: { |
| 16 | + type: 'suggestion', |
| 17 | + docs: { |
| 18 | + description: |
| 19 | + "It's preferred to avoid multiple assertions in `waitFor`", |
| 20 | + category: 'Best Practices', |
| 21 | + recommended: false, |
| 22 | + }, |
| 23 | + messages: { |
| 24 | + noMultipleAssertionWaitFor: 'Avoid using multiple assertions within `waitFor` callback', |
| 25 | + }, |
| 26 | + fixable: null, |
| 27 | + schema: [], |
| 28 | + }, |
| 29 | + defaultOptions: [], |
| 30 | + create: function(context) { |
| 31 | + function reportMultipleAssertion( |
| 32 | + node: TSESTree.BlockStatement |
| 33 | + ) { |
| 34 | + const totalExpect = (body: Array<TSESTree.Node>): Array<TSESTree.Node> => |
| 35 | + body.filter((node: TSESTree.ExpressionStatement) => { |
| 36 | + if ( |
| 37 | + isCallExpression(node.expression) && |
| 38 | + isMemberExpression(node.expression.callee) && |
| 39 | + isCallExpression(node.expression.callee.object) |
| 40 | + ) { |
| 41 | + const object: TSESTree.CallExpression = node.expression.callee.object |
| 42 | + const expressionName: string = isIdentifier(object.callee) && object.callee.name |
| 43 | + return expressionName === 'expect' |
| 44 | + } else { |
| 45 | + return false |
| 46 | + } |
| 47 | + }) |
| 48 | + |
| 49 | + if (isBlockStatement(node) && totalExpect(node.body).length > 1) { |
| 50 | + context.report({ |
| 51 | + node, |
| 52 | + loc: node.loc.start, |
| 53 | + messageId: 'noMultipleAssertionWaitFor', |
| 54 | + }); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return { |
| 59 | + [`${WAIT_EXPRESSION_QUERY} > ArrowFunctionExpression > BlockStatement`]: reportMultipleAssertion, |
| 60 | + [`${WAIT_EXPRESSION_QUERY} > FunctionExpression > BlockStatement`]: reportMultipleAssertion, |
| 61 | + }; |
| 62 | + } |
| 63 | +}) |
0 commit comments