[英]How to avoid time in a test when expecting a Promise with setTimeout in Jasmine
鑒於我有以下代碼:
public returnData(): Promise<any> {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
data: true,
});
}, 2000);
});
}
現在,目前我的單元測試成功地做到了:
it('should return data', async function () {
const responseMock = {
data: true,
};
await expectAsync(component.returnData()).toBeResolvedTo(responseMock);
});
但是有一個明顯的問題:測試耗時超過2000ms,無法接受。 我希望能夠在無需等待時間的情況下對此進行測試。 我嘗試了許多不同的解決方案,如下所示:
it('should return data', async function () {
jasmine.clock().install();
const responseMock = {
data: true,
};
setTimeout(() => {
expectAsync(component.returnData()).toBeResolvedTo(responseMock);
jasmine.clock().tick(2000);
}, 2000);
jasmine.clock().uninstall();
});
上面的測試通過了很好的時機,但是當我將responseMock
值更改為其他任何值時,它仍然通過了,所以它並沒有真正工作......
測試這個特定案例的關鍵是什么,而不需要等待 setTimeout 時間?
你為什么在setTimeout
中運行期望? 也許我們不需要那個。
嘗試這個:
it('should return data', async function () {
jasmine.clock().install();
const responseMock = {
data: true,
};
// call the method that returns a promise and have a handle on its promise
const promise = component.returnData();
// make 2 seconds pass in a fake way
jasmine.clock().tick(2000);
// await the promise
const result = await promise;
// assert the result
expect(result).toEqual(responseMock);
jasmine.clock().uninstall();
});
我看到你正在使用component.
並且很可能您正在使用 Angular。 如果您使用的是 Angular,我使用fakeAsync/tick
來表示時間和承諾。
在這里查看fakeAsync/tick
。
//
it('should return data', fakeAsync(() => {
const responseMock = {
data: true,
};
// call the method that returns a promise and have a handle on its promise
const promise = component.returnData();
// make 2000 pass in a fake way
tick(2000);
promise.then(result => {
expect(result).toEqual(responseMock);
expect(1).toBe(2); // delete this - make sure the test fails to know we made it here
});
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.