angular - 如何测试 Promise then 方法
问题描述
如何测试 Promise 的 then() 方法中的代码。我没有看到代码的 then(..) 方法中的代码覆盖率。我的单元测试通过并且没有抛出错误,但是当我查看行覆盖率时, toPromise.then(//this 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();
});
});
解决方案
那是因为异步任务。您的测试在承诺之前结束,因此then
永远不会调用回调。
只需更改您的测试即可处理async
方法一
fakeAsync
Angular 提供的使用: https ://angular.io/api/core/testing/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();
}));
方法二
async/await
从 ES2016 开始
使用: https ://developer.mozilla.org/en-US/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();
});
方法三
当测试应该以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();
});
推荐阅读
- python - Web 抓取未通过 Selenium/BS4 获取完整的源代码数据
- c++ - 如何使用派生类的虚函数,在另一个类中用基类参数声明?
- angular - 动态创建的变量没有作用域?
- c# - 旋转图像的精度
- r - 保存 qgraph 在 for 循环中不起作用,但在外部
- php - PHP 扩展 mysqli 和 nd_mysqli 的区别
- android - DAGGER:尝试注入 Fragment 时错误无法解决“this”?
- loops - 当可变引用存在时传递不可变引用
- arrays - 数组的最小元素
- javascript - angular catch beforeinstallprompt 事件,添加到开发工具中的主屏幕 > 应用程序不做任何事情