[英]How to test Promise then method
如何在Promise的then()方法中測試代碼。 我的代碼的then(..)方法內部沒有看到代碼的代碼覆蓋率。 我的單元測試通過並沒有引發任何錯誤,但是當我查看行覆蓋率時,toPromise.then(//此代碼)內部的代碼未覆蓋。 我如何測試該代碼。
//service file
getDataFromAPI(num: string): Promise<Model> {
return this._http
.get<Model>('url')
.toPromise()
.then(resolve => {
const { item1, item2, item3 } = resolve;
return { item1, item2, item3 };
});
}
//unit test
describe('getDataFromAPI', () => {
it('should get data', () => {
const service: Service = TestBed.get(Service);
const httpClientGetSpy = jest.spyOn(httpClient, 'get');
service.getDataFromAPI(num).then(response => {
expect(response.item1).toEqual('one');
expect(response.item2).toEqual('two');
expect(response.item3).toEqual('three');
});
expect(httpClientGetSpy).toHaveBeenCalled();
});
});
那是因為異步任務。 承諾之前,您的測試結束,以便then
回調永遠不會被調用。
只需更改測試以處理async
方法1
使用fakeAsync
提供的fakeAsync
: https : fakeAsync
it('should get data', fakeAsync(() => {
const service: Service = TestBed.get(Service);
const httpClientGetSpy = jest.spyOn(httpClient, 'get');
service.getDataFromAPI(num).then(response => {
expect(response.item1).toEqual('one');
expect(response.item2).toEqual('two');
expect(response.item3).toEqual('three');
});
expect(httpClientGetSpy).toHaveBeenCalled();
}));
方法2
從ES2016開始使用async/await
: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/await
it('should get data', async() => {
const service: Service = TestBed.get(Service);
const httpClientGetSpy = jest.spyOn(httpClient, 'get');
let response = await service.getDataFromAPI(num);
expect(response.item1).toEqual('one');
expect(response.item2).toEqual('two');
expect(response.item3).toEqual('three');
expect(httpClientGetSpy).toHaveBeenCalled();
});
方法3
處理何時應以done
功能結束測試:
it('should get data', (done) => {
const service: Service = TestBed.get(Service);
const httpClientGetSpy = jest.spyOn(httpClient, 'get');
service.getDataFromAPI(num).then(response => {
expect(response.item1).toEqual('one');
expect(response.item2).toEqual('two');
expect(response.item3).toEqual('three');
done();
});
expect(httpClientGetSpy).toHaveBeenCalled();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.