Skip to content

Commit 9f1832f

Browse files
committed
feat: add auto-fix for no-wait-for-side-effects
1 parent bd01e08 commit 9f1832f

File tree

1 file changed

+46
-4
lines changed

1 file changed

+46
-4
lines changed

lib/rules/no-wait-for-side-effects.ts

Lines changed: 46 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@ export default createTestingLibraryRule<Options, MessageIds>({
4242
},
4343
defaultOptions: [],
4444
create(context, _, helpers) {
45+
const sourceCode = getSourceCode(context);
46+
4547
function isCallerWaitFor(
4648
node:
4749
| TSESTree.AssignmentExpression
@@ -155,8 +157,6 @@ export default createTestingLibraryRule<Options, MessageIds>({
155157
}
156158
return false;
157159
});
158-
159-
return false;
160160
}
161161

162162
function getSideEffectNodes(
@@ -195,7 +195,17 @@ export default createTestingLibraryRule<Options, MessageIds>({
195195
}) as TSESTree.ExpressionStatement[];
196196
}
197197

198-
function reportSideEffects(node: TSESTree.BlockStatement) {
198+
function reportSideEffects(
199+
node: TSESTree.BlockStatement & {
200+
parent: (
201+
| TSESTree.ArrowFunctionExpression
202+
| TSESTree.FunctionDeclaration
203+
| TSESTree.FunctionExpression
204+
) & {
205+
parent: TSESTree.CallExpression;
206+
};
207+
}
208+
) {
199209
if (!isCallerWaitFor(node)) {
200210
return;
201211
}
@@ -208,6 +218,38 @@ export default createTestingLibraryRule<Options, MessageIds>({
208218
context.report({
209219
node: sideEffectNode,
210220
messageId: 'noSideEffectsWaitFor',
221+
fix(fixer) {
222+
const { parent: callExpressionNode } = node.parent;
223+
const targetNode = isAwaitExpression(callExpressionNode.parent)
224+
? callExpressionNode.parent
225+
: callExpressionNode;
226+
const lines = sourceCode.getText().split('\n');
227+
228+
const line = lines[targetNode.loc.start.line - 1];
229+
230+
const indent = line.match(/^\s*/)?.[0] ?? '';
231+
const lineStart = sourceCode.getIndexFromLoc({
232+
line: sideEffectNode.loc.start.line,
233+
column: 0,
234+
});
235+
const lineEnd = sourceCode.getIndexFromLoc({
236+
line: sideEffectNode.loc.end.line + 1,
237+
column: 0,
238+
});
239+
240+
const sideEffectLines = lines.slice(
241+
sideEffectNode.loc.start.line - 1,
242+
sideEffectNode.loc.end.line
243+
);
244+
const sideEffectNodeText = sideEffectLines.join('\n');
245+
return [
246+
fixer.insertTextBefore(
247+
targetNode,
248+
sideEffectNodeText.trimStart() + '\n' + indent
249+
),
250+
fixer.removeRange([lineStart, lineEnd]),
251+
];
252+
},
211253
})
212254
);
213255
}
@@ -260,7 +302,7 @@ export default createTestingLibraryRule<Options, MessageIds>({
260302
const targetNode = isAwaitExpression(callExpressionNode.parent)
261303
? callExpressionNode.parent
262304
: callExpressionNode;
263-
const sourceCode = getSourceCode(context);
305+
264306
return fixer.replaceText(targetNode, sourceCode.getText(node));
265307
},
266308
});

0 commit comments

Comments
 (0)