|
8 | 8 | ModifierName,
|
9 | 9 | createRule,
|
10 | 10 | getAccessorValue,
|
| 11 | + getSourceCode, |
| 12 | + isFunction, |
11 | 13 | isSupportedAccessor,
|
12 | 14 | parseJestFnCallWithReason,
|
13 | 15 | } from './utils';
|
@@ -48,6 +50,18 @@ const findPromiseCallExpressionNode = (node: TSESTree.Node) =>
|
48 | 50 | ? getPromiseCallExpressionNode(node.parent)
|
49 | 51 | : null;
|
50 | 52 |
|
| 53 | +const findFirstAsyncFunction = ({ |
| 54 | + parent, |
| 55 | +}: TSESTree.Node): TSESTree.Node | null => { |
| 56 | + if (!parent) { |
| 57 | + return null; |
| 58 | + } |
| 59 | + |
| 60 | + return isFunction(parent) && parent.async |
| 61 | + ? parent |
| 62 | + : findFirstAsyncFunction(parent); |
| 63 | +}; |
| 64 | + |
51 | 65 | const getParentIfThenified = (node: TSESTree.Node): TSESTree.Node => {
|
52 | 66 | const grandParentNode = node.parent?.parent;
|
53 | 67 |
|
@@ -127,6 +141,7 @@ export default createRule<[Options], MessageIds>({
|
127 | 141 | promisesWithAsyncAssertionsMustBeAwaited:
|
128 | 142 | 'Promises which return async assertions must be awaited{{ orReturned }}',
|
129 | 143 | },
|
| 144 | + fixable: 'code', |
130 | 145 | type: 'suggestion',
|
131 | 146 | schema: [
|
132 | 147 | {
|
@@ -339,6 +354,25 @@ export default createRule<[Options], MessageIds>({
|
339 | 354 | ? 'asyncMustBeAwaited'
|
340 | 355 | : 'promisesWithAsyncAssertionsMustBeAwaited',
|
341 | 356 | node,
|
| 357 | + fix(fixer) { |
| 358 | + if (!findFirstAsyncFunction(finalNode)) { |
| 359 | + return []; |
| 360 | + } |
| 361 | + const returnStatement = |
| 362 | + finalNode.parent?.type === AST_NODE_TYPES.ReturnStatement |
| 363 | + ? finalNode.parent |
| 364 | + : null; |
| 365 | + |
| 366 | + if (alwaysAwait && returnStatement) { |
| 367 | + const sourceCodeText = |
| 368 | + getSourceCode(context).getText(returnStatement); |
| 369 | + const replacedText = sourceCodeText.replace('return', 'await'); |
| 370 | + |
| 371 | + return fixer.replaceText(returnStatement, replacedText); |
| 372 | + } |
| 373 | + |
| 374 | + return fixer.insertTextBefore(finalNode, 'await '); |
| 375 | + }, |
342 | 376 | });
|
343 | 377 |
|
344 | 378 | if (isParentArrayExpression) {
|
|
0 commit comments