javascript - Angular 单元测试:如何对 .map() 进行单元测试?
问题描述
我需要测试一种服务方法,但我不确定如何为调用某些注入服务方法而运行的部分代码实现 100% 的代码覆盖率。
待测服务方式:
@Injectable()
export class BomRevisiosnsService {
constructor(
private baseService: BaseService,
private appConstants: AppConstants,
private dmConstants: DMConstants
) { }
public getRevisionsData(): any {
var itemId = this.appConstants.userPreferences.modelData['basicDetails']['itemId'];
let url = this.dmConstants.URLs.GETBOMREVISIONS + itemId + "/GetRevisionsAsync";
let headers = {
"Content-Type": "application/json",
UserExecutionContext: JSON.stringify(this.appConstants.userPreferences.UserBasicDetails),
}
if (itemId != null || itemId != undefined) {
return this.baseService.getData(url, headers)
.map(response => {
// this area not getting covered.
return response;
});
}
}
}
我如何覆盖:
.map(response => {
return response;
});
在下面的:
测试:
it('should return response if itemId is not null or undefined', () => {
let mockData = [1,2,3];
let mockObservable = Observable.of(mockData);
spyOn(baseService, 'getData').and.returnValue(mockObservable);
appConstants.userPreferences.modelData['basicDetails']['itemId']=4; // itemId not null or undefined
dMConstants.URLs.GETBOMREVISIONS ="dummy url";
subject.getRevisionsData();
expect(baseService.getData).toBe(mockData); // How do I test .map()?
});
解决方案
it('should return response if itemId is not null or undefined', () => {
...
const spy = spyOn(baseService.getData).and.return(mockedData)// you need to define data returned by baseService.getData
const result = subject.getRevisionsData();
expect(spy).toHaveBeenCalled(); // How do I test .map()?
expect(result).toEqual(mockedData);// for simple map it will be the same thing that is returned for more complicated map it may differ
});
推荐阅读
- mysql - MySQL SELECT JOIN 与空行返回
- ionic-framework - Leaflet - 如何将点击事件添加到离子应用程序中的标记弹出内的按钮?
- r - 取消嵌套数据框中的列,在某些列中有多个嵌套列表
- r - 时间序列降水分析的正确日期格式
- kotlin - 尝试在 Kotlin 的片段中使用 Zelory 压缩器
- mips - 在 6 级标量或超标量 MIPS 中,如果发生错误预测,需要杀死多少条指令?
- aws-lambda - AWS Fargate 与 Lambda 与预置并发
- node.js - UnhandledPromiseRejectionWarning:错误:需要数据和盐参数
- spring-boot - 如何使用 undertow 在 Spring Boot 中禁用管理上下文访问日志
- google-apps-script - 谷歌应用脚本导出 csv 用分号而不是逗号