[英]how to correctly import an asynchronous module.exports function in javascript
我在名為 index.js 的文件中編寫了一個異步 function,如下所示:
module.exports.func = async (obj) => {
return {
statusCode: 200,
body: JSON.stringify({
message: 'Success!',
input: obj,
}),
};
};
但是,當我嘗試使用以下代碼編寫名為 index.test.js 的測試文件時:
const exportedModule = require('./index');
test('Successfully execute func when empty object passed', () => {
const obj = {};
const expectedReturn = {
statusCode: 200,
body: JSON.stringify({
message: 'Success!',
input: obj,
}),
};
const actualReturn = await exportedModule.func(obj);
console.log(actualReturn);
expect(actualReturn).toBe(expectedReturn);
});
,我得到一個錯誤,說exportedModule.func
不是異步的,即使通過它顯然是。 我不能使用承諾( .then
和.catch
)來運行測試,因為測試文件將在.then
/ .catch
中的代碼執行之前被視為完成。 有沒有辦法讓我正確導入func
以便我可以使用await
? 理想情況下,我希望在不更改 index.js 的情況下在測試文件本身內完成此操作。
我收到一條錯誤消息,指出 exportedModule.func 不是異步的
我認為你誤讀了錯誤。 它說您測試中的 function 不是async
。 您只能在async
function 中使用await
。要修復它,請將async
添加到 function。
// added: VVVVV
test('Successfully execute func when empty object passed', async () => {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.