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