[英]Jest test for async promise with async/await
我有這個 function 返回一個 promise 並在調用時失敗:
export const mockAsync = () => {
return new Promise((_, reject) => {
setTimeout(() => reject(new Error('Error')), 50);
});
};
我有這個測試,它正在通過:
describe('mockAsync', () => {
test('it should throw if we ask for it', async () => {
const result = mockAsync();
await expect(result).rejects.toThrow('Error');
});
});
但我覺得很奇怪,我希望它在 function 調用之前調用await
:
describe('mockAsync', () => {
test('it should throw if we ask for it', async () => {
const result = await mockAsync();
expect(result).rejects.toThrow('Error');
});
});
最后一個沒有通過,我不明白為什么。 是不是語法正確?
對於測試,您希望 promise 在期望的上下文中被拒絕。 出於這個原因,我們通常這樣寫:
await expect(/*sync function call*/).rejects.toThrow('someError')
在您的特定示例中:
describe('mockAsync', () => {
test('it should throw if we ask for it', async () => {
await expect(mockAsync()).rejects.toThrow('Error')
})
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.