angular - Jasmine 的代码覆盖率中未涵盖 if else 语句
问题描述
当我使用 Jasmine 弹珠对 if 条件进行单元测试时,这些特定块未包含在代码覆盖率报告中。有没有办法对 if 块进行单元测试,以便在代码覆盖率报告中涵盖它们?
activeClass(menu: MenuList): void {
this.menuList && this.menuList.map((element: MenuList) => {
if (element.menu_name === menu.menu_name) {
element.active = true;
this.gotoSelectedRoute(element);
} else {
element.active = false;
}
});
}
const menuList: MenuList[] = [{
menu_name: 'MENU_LIST.NEW_BOOKING',
class: '',
url: 'services',
is_hosted: true,
is_shown_login: true,
showOnCondition: 'isHostedWithLogin',
is_hide_login: true,
hidden: false,
displayOrder: 1,
options: null,
active: false,
}, ];
describe('activeClass', (): void => {
const menu: MenuList = menuList[0];
const menuListdata: MenuList[] = menuList;
it('should call activeClass', fakeAsync(() => {
selectMenuDataMock.setResult(menuList);
store.refreshState();
fixture.detectChanges();
component.activeClass(menuList[0]);
expect(component.activeClass).toBeTruthy();
}));
it('should both the menu name needs to be same', fakeAsync(() => {
selectMenuDataMock.setResult(menuList);
store.refreshState();
fixture.detectChanges();
component.activeClass(menu);
menuList.forEach((element) => {
element.menu_name = 'MENU_LIST.NEW_BOOKING';
menu.menu_name = 'MENU_LIST.NEW_BOOKING';
expect(element.menu_name).toEqual(menu.menu_name);
});
}));
it('should active be true', fakeAsync(() => {
selectMenuDataMock.setResult(menuList);
store.refreshState();
fixture.detectChanges();
component.activeClass(menu);
menu.active = true;
menuList.forEach((element) => {
expect(element.active).toBe(true);
});
}));
it('should gotoselected', fakeAsync(() => {
selectMenuDataMock.setResult(menuList);
store.refreshState();
fixture.detectChanges();
component.activeClass(menu);
const spy = spyOn(component, 'gotoSelectedRoute').and.callThrough();
menuList.forEach((element) => {
element.active = true;
component.gotoSelectedRoute(element);
expect(spy).toHaveBeenCalledWith(element);
});
}));
it('should active be false', fakeAsync(() => {
selectMenuDataMock.setResult(menuList);
store.refreshState();
fixture.detectChanges();
component.activeClass(menu);
menu.active = false;
menuList.forEach((element) => {
expect(element.active).toBe(false);
});
}));
});
不确定单元测试的编码风格是否正确,如果需要任何改进,请告诉我。
从上面的 ts 文件中,如果没有覆盖块代码,不确定我要去哪里
这是我正在尝试写的情况谢谢。
解决方案
您没有覆盖 if 语句的原因是您的 component.menuList 为空。由于 menuList 为空,因此代码不会打扰运行您的地图功能。
要纠正,只需在调用 activeClass 函数之前给您的 component.menuList 一个有效值。
推荐阅读
- visual-studio-2017 - Visual Studio 2017“在文件中查找” - 窗口不显示
- dart - Flutter Android 警报管理器无法正常工作
- apache - htacess 在端口中使用 https
- angular - 如何在 Azure AD 认证的 Azure 函数中获取用户信息
- ios - 通过Alamofire,想获取数据并将其插入TableView,但在插入完成之前,TableView被加载
- java - Firebase GeoFire setlocation 在服务中不起作用
- corda - 运行 deployNodes 时失败
- spring - 计划任务是否应该在每次执行时启动 Spring 应用程序?
- ios - 如何查看应用内购买(自动续订)的购买状态?
- android - 使用 Kotlin 在 Android 中复制文件 Flutter 插件