我最近发现了 jscodeshift 并利用它进行重构。
但是我找不到在我正在寻找的节点之前添加 await
的方法。
// AS-IS
userEvent.click(a);
await userEvent.click(b);
// TO-BE
await userEvent.click(a);
await userEvent.click(b);
这就是我查询userEvent.click
const getFunctionCall = (obj:string, prop:string) => {
return source.find(j.CallExpression, {
callee: {
type: 'MemberExpression',
object: {
name: obj
},
property: {
name:prop
}
}
})
}
const clicks = getFunctionCall('userEvent', 'click');
clicks.forEach(i=> {
if (i.parentPath.value.type !== 'AwaitExpression') {
// code goes here
}
})
在这种情况下,如何在 userEvent
之前添加 await
并使其余代码保持不变?
我查看了 document了解如何构建语句或表达式,但这对我来说是无法理解的,因为我刚刚开始使用它。如果您能为这个图书馆介绍一些好的资料,我将不胜感激。
提前致谢!
最佳答案
很简单,您需要将现有的 CallExpression 包装在一个等待表达式中,如下所示:
// Press ctrl+space for code completion
export default function transformer(file, api) {
const j = api.jscodeshift;
const root = j(file.source);
const body = root.get().value.program.body;
root.find(j.CallExpression, {
callee: {
object: {
name: "userEvent"
},
property: {
name: "click"
}
}
}).filter(path => {
return path.value.arguments[0].name === "a" ;
}).replaceWith(path => {
return j.awaitExpression(path.value)
});
return root.toSource();
}
关于javascript - 如何使用jscodeshift在节点添加 'await'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72733345/