|
| 1 | +import { ESLintUtils, TSESTree } from '@typescript-eslint/experimental-utils'; |
| 2 | +import { getDocsUrl, SYNC_EVENTS } from '../utils'; |
| 3 | +import { isObjectExpression, isProperty, isIdentifier } from '../node-utils'; |
| 4 | +export const RULE_NAME = 'no-await-sync-events'; |
| 5 | +export type MessageIds = 'noAwaitSyncEvents'; |
| 6 | +type Options = []; |
| 7 | + |
| 8 | +const SYNC_EVENTS_REGEXP = new RegExp(`^(${SYNC_EVENTS.join('|')})$`); |
| 9 | +export default ESLintUtils.RuleCreator(getDocsUrl)<Options, MessageIds>({ |
| 10 | + name: RULE_NAME, |
| 11 | + meta: { |
| 12 | + type: 'problem', |
| 13 | + docs: { |
| 14 | + description: 'Disallow unnecessary `await` for sync events', |
| 15 | + category: 'Best Practices', |
| 16 | + recommended: 'error', |
| 17 | + }, |
| 18 | + messages: { |
| 19 | + noAwaitSyncEvents: '`{{ name }}` does not need `await` operator', |
| 20 | + }, |
| 21 | + fixable: null, |
| 22 | + schema: [], |
| 23 | + }, |
| 24 | + defaultOptions: [], |
| 25 | + |
| 26 | + create(context) { |
| 27 | + // userEvent.type() is an exception, which returns a |
| 28 | + // Promise. But it is only necessary to wait when delay |
| 29 | + // option is specified. So this rule has a special exception |
| 30 | + // for the case await userEvent.type(element, 'abc', {delay: 1234}) |
| 31 | + return { |
| 32 | + [`AwaitExpression > CallExpression > MemberExpression > Identifier[name=${SYNC_EVENTS_REGEXP}]`]( |
| 33 | + node: TSESTree.Identifier |
| 34 | + ) { |
| 35 | + const memberExpression = node.parent as TSESTree.MemberExpression; |
| 36 | + const methodNode = memberExpression.property as TSESTree.Identifier; |
| 37 | + const callExpression = memberExpression.parent as TSESTree.CallExpression; |
| 38 | + const withDelay = callExpression.arguments.length >= 3 && |
| 39 | + isObjectExpression(callExpression.arguments[2]) && |
| 40 | + callExpression.arguments[2].properties.some( |
| 41 | + property => |
| 42 | + isProperty(property) && |
| 43 | + isIdentifier(property.key) && |
| 44 | + property.key.name === 'delay' |
| 45 | + ); |
| 46 | + |
| 47 | + if (!(node.name === 'userEvent' && methodNode.name === 'type' && withDelay)) { |
| 48 | + context.report({ |
| 49 | + node: methodNode, |
| 50 | + messageId: 'noAwaitSyncEvents', |
| 51 | + data: { |
| 52 | + name: `${node.name}.${methodNode.name}`, |
| 53 | + }, |
| 54 | + }); |
| 55 | + } |
| 56 | + }, |
| 57 | + }; |
| 58 | + }, |
| 59 | +}); |
0 commit comments