【发布时间】:2021-05-19 20:57:18
【问题描述】:
当我使用 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 文件中不确定我要去哪里
这是我正在尝试写的情况谢谢。
【问题讨论】:
-
this.menuList看起来它可能没有被初始化,所以代码没有被调用。大概selectMenuDataMock.setResult(menuList); store.refreshState(); fixture.detectChanges();应该设置它。如果您在activeClass中设置断点,this.menuList是否与您期望的一样? -
@possum 是的,就像我期望的那样