[英]How to test Promise then method
How do I test the code inside the then() method of a Promise. 如何在Promise的then()方法中测试代码。 I do not see code coverage for the code inside the then(..) method of my code. 我的代码的then(..)方法内部没有看到代码的代码覆盖率。 My unit test passes and throws no errors, but when I look at line coverage, the code inside toPromise.then(//this code) is not covered. 我的单元测试通过并没有引发任何错误,但是当我查看行覆盖率时,toPromise.then(//此代码)内部的代码未覆盖。 How do I test that code. 我如何测试该代码。
//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();
});
});
That's because of asynchronous task. 那是因为异步任务。 Your test end before promise so then
callback is never called. 承诺之前,您的测试结束,以便then
回调永远不会被调用。
Just change your test to handle async
只需更改测试以处理async
Method 1 方法1
Use fakeAsync
provided by Angular : https://angular.io/api/core/testing/fakeAsync 使用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();
}));
Method 2 方法2
Use async/await
from ES2016 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await 从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();
});
Method 3 方法3
Handle when test should be ended with done
function : 处理何时应以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.