[英]Jasmine Test : How to test Promise.then() block?
我想測試一個場景,我正在調用一個 function(它返回一個承諾),然后在 then 塊中,我正在調用另一個名為“ calledInThenBlock()”的 function。 我想測試當 then 塊執行時,名為 count 的組件變量的值設置為 2,並調用了 calledInThenBlock()。
testIt(){
this.returnPromise().then((res)=>{
if(res.data[0].name=="Ankit"){
this.count=2;
this.calledInThenBlock();
}
}).catch(()=>{
this.calledInCatchBlock();
})
}
returnPromise(){
return Promise.resolve({data:[{name:"Ankit"}]});
}
我無法弄清楚如何測試這種情況。 任何建議,將不勝感激。
謝謝!
在您的代碼中,您無需等待 Promise 解決。
testIt() {
// testIt() returns before the Promise returned by returnPromise() is
// resolved.
this.returnPromise().then((res) => {
if (res.data[0].name == "Ankit") {
this.count = 2;
this.calledInThenBlock();
}
}).catch(() => {
this.calledInCatchBlock();
})
}
it('test testIt()', () => {
testIt();
// okay, now how do I know when the Promise returned by returnPromise()
// is resolved? Or when the value of count will change?
// Of course, I can make it work by calling the assertions after an
// arbitrary amount of time, but it doesn't seem like the natural way
// of doing things.
});
代碼很臭。 依賴於testIt()
的客戶端將期望知道它執行的工作何時完成。 編寫單元測試時也會變得很麻煩。 在testIt()
調用之后在測試用例中做出的任何斷言都可能在 Promise 解析之前得到評估。 將您的 function 更改為以下將修復它。
testIt() async {
try {
const res = await this.returnPromise(); // wait for the Promise to resolve
if (res.data[0].name == "Ankit") {
this.count = 2;
this.calledInThenBlock();
}
} catch (e) {
this.calledInCatchBlock();
}
}
要編寫異步測試,您可以使用async/await
和 Jasmine來解決測試期間返回的承諾。
it('test Example#testIt()', async () => {
const example = new Example(); // or however you instantiate it.
await example.testIt(); // wait for the Promise to resolve
// followed by assertions to validate behaviour correctness.
expect(example.count).toEqual(2);
});
我提供的代碼僅用於說明目的。 它可能無法按原樣工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.