如何测试是否使用 async 关键字调用函数
How to test if function is called with async keyword
我想为我的 vue3 应用程序编写一个简单的测试,测试应该断言特定函数(在本例中为 updateRoute)是用 async[= 声明的31=] 在不同的组件中
注意:根据我目前的项目,我无法将此功能隔离在单个文件中以使其可重用
示例:
const updateRoute = () => { doSomethig() }
应该失败
而
const updateRoute = async () => { await doSomethig() }
应该通过
测试库无关紧要,它可以是 Jest 或其他任何东西
检查函数的contructor.name
是否等于'AsyncFunction'
:
const x = async () => {};
const y = () => {}
console.log(x.constructor.name);
console.log(x.constructor.name === 'AsyncFunction');
console.log(y.constructor.name);
console.log(y.constructor.name === 'AsyncFunction');
有no reliable way and no reason检测async
功能。对于一个 returns promise 的函数,它等同于:
const updateRoute = () => {
return doSomethig().then(() => {}) // Returns a promise of undefined
}
应该测试updateRoute
returns一个promise,有没有async
。在 Jest 中是:
expect(updateRoute()).toEqual(expect.any(Promise));
至于强制性的await
,必要时可以用ESLint require-await
rule处理。
我想为我的 vue3 应用程序编写一个简单的测试,测试应该断言特定函数(在本例中为 updateRoute)是用 async[= 声明的31=] 在不同的组件中
注意:根据我目前的项目,我无法将此功能隔离在单个文件中以使其可重用
示例:
const updateRoute = () => { doSomethig() }
应该失败
而
const updateRoute = async () => { await doSomethig() }
应该通过
测试库无关紧要,它可以是 Jest 或其他任何东西
检查函数的contructor.name
是否等于'AsyncFunction'
:
const x = async () => {};
const y = () => {}
console.log(x.constructor.name);
console.log(x.constructor.name === 'AsyncFunction');
console.log(y.constructor.name);
console.log(y.constructor.name === 'AsyncFunction');
有no reliable way and no reason检测async
功能。对于一个 returns promise 的函数,它等同于:
const updateRoute = () => {
return doSomethig().then(() => {}) // Returns a promise of undefined
}
应该测试updateRoute
returns一个promise,有没有async
。在 Jest 中是:
expect(updateRoute()).toEqual(expect.any(Promise));
至于强制性的await
,必要时可以用ESLint require-await
rule处理。