Skip to content

Commit e56ce4d

Browse files
committed
feat: add 'fixable' to valid-expect
1 parent 8001fe7 commit e56ce4d

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/rules/valid-expect.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import {
88
ModifierName,
99
createRule,
1010
getAccessorValue,
11+
getSourceCode,
12+
isFunction,
1113
isSupportedAccessor,
1214
parseJestFnCallWithReason,
1315
} from './utils';
@@ -48,6 +50,18 @@ const findPromiseCallExpressionNode = (node: TSESTree.Node) =>
4850
? getPromiseCallExpressionNode(node.parent)
4951
: null;
5052

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+
5165
const getParentIfThenified = (node: TSESTree.Node): TSESTree.Node => {
5266
const grandParentNode = node.parent?.parent;
5367

@@ -127,6 +141,7 @@ export default createRule<[Options], MessageIds>({
127141
promisesWithAsyncAssertionsMustBeAwaited:
128142
'Promises which return async assertions must be awaited{{ orReturned }}',
129143
},
144+
fixable: 'code',
130145
type: 'suggestion',
131146
schema: [
132147
{
@@ -339,6 +354,25 @@ export default createRule<[Options], MessageIds>({
339354
? 'asyncMustBeAwaited'
340355
: 'promisesWithAsyncAssertionsMustBeAwaited',
341356
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+
},
342376
});
343377

344378
if (isParentArrayExpression) {

0 commit comments

Comments
 (0)