|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const { getDocsUrl } = require('../utils'); |
| 4 | + |
| 5 | +function isAwaited(node) { |
| 6 | + return VALID_PARENTS.includes(node.type); |
| 7 | +} |
| 8 | + |
| 9 | +function hasThenProperty(node) { |
| 10 | + return node.type === 'MemberExpression' && node.property.name === 'then'; |
| 11 | +} |
| 12 | + |
| 13 | +function isPromiseResolved(node) { |
| 14 | + const parent = node.parent.parent; |
| 15 | + |
| 16 | + // fireEvent.click().then(...) |
| 17 | + if (parent.type === 'CallExpression') { |
| 18 | + return hasThenProperty(parent.parent); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +const VALID_PARENTS = [ |
| 23 | + 'AwaitExpression', |
| 24 | + 'ArrowFunctionExpression', |
| 25 | + 'ReturnStatement', |
| 26 | +]; |
| 27 | + |
| 28 | +module.exports = { |
| 29 | + meta: { |
| 30 | + type: 'problem', |
| 31 | + docs: { |
| 32 | + description: 'Enforce async fire event methods to be awaited', |
| 33 | + category: 'Best Practices', |
| 34 | + recommended: false, |
| 35 | + url: getDocsUrl('await-fire-event'), |
| 36 | + }, |
| 37 | + messages: { |
| 38 | + awaitFireEvent: 'async `fireEvent.{{ methodName }}` must be awaited', |
| 39 | + }, |
| 40 | + fixable: null, |
| 41 | + schema: [], |
| 42 | + }, |
| 43 | + |
| 44 | + create: function(context) { |
| 45 | + return { |
| 46 | + 'CallExpression > MemberExpression > Identifier[name=fireEvent]'(node) { |
| 47 | + const fireEventMethodNode = node.parent.property; |
| 48 | + |
| 49 | + if ( |
| 50 | + !isAwaited(node.parent.parent.parent) && |
| 51 | + !isPromiseResolved(fireEventMethodNode) |
| 52 | + ) { |
| 53 | + context.report({ |
| 54 | + node: fireEventMethodNode, |
| 55 | + messageId: 'awaitFireEvent', |
| 56 | + data: { |
| 57 | + methodName: fireEventMethodNode.name, |
| 58 | + }, |
| 59 | + }); |
| 60 | + } |
| 61 | + }, |
| 62 | + }; |
| 63 | + }, |
| 64 | +}; |
0 commit comments