首页 > 解决方案 > 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 文件中,如果没有覆盖块代码,不确定我要去哪里

这是我正在尝试写的情况谢谢。

在此处输入图像描述

标签: angularjasmine

解决方案


您没有覆盖 if 语句的原因是您的 component.menuList 为空。由于 menuList 为空,因此代码不会打扰运行您的地图功能。

要纠正,只需在调用 activeClass 函数之前给您的 component.menuList 一个有效值。


推荐阅读