首页 > 解决方案 > 功能单元测试中未涵盖的 if 语句 - Jasmine

问题描述

我正在为某个代码编写 jasmine 测试用例。我已经介绍了组件中的函数,但没有介绍函数中的 if 语句。以下是未涵盖的函数中的 if 语句。

 ngOnChanges(changes: SimpleChanges) {
 this.branchuserRole = this.userService.getUser().getId();
 if (this.data) {
  if (this.branchuserRole === this.TEST) {
    this.data = this.data.filter(task => task.assignedUser !== null);
    this.data = this.data.filter(task => task.assignedRole === this.TEST);
    this.summaryListLength = this.data.length;
  } else {
    this.summaryListLength = this.data.length;
  }

整个 if else 部分不在代码覆盖范围内。下面是我试过的代码。

it('should call ngOnChanges function', () => {
    const changes: any = '';
    spyOn(component, 'ngOnChanges').and.callThrough();
    component.ngOnChanges(changes);
    expect(component.ngOnChanges).toHaveBeenCalled();
});
it('should set the value of data', () => {
    const changes: any = '';
    component.ngOnChanges(changes);
    component.branchuserRole = TEST;
    expect(component.data).toBeTruthy();
    expect(component.data).toEqual(component.data.filter(task => task.assignedUser !== null));
    expect(component.taskData).toEqual(component.taskData.filter(
        task => task.assignedRole === TEST));
    expect(component.summaryListLength).toEqual(component.data.length);
});

标签: angulartypescriptkarma-jasmine

解决方案


不要忘记您有一个应该返回 branchuserRole 的服务。因此,您必须在 TestBed 中初始化服务,然后您需要对其进行 spy 并返回您想要的值。这就是为什么您不能使用 branchUserRole 跳过 if 语句的原因。现在您只需使用 TEST 初始化 branchUserRole(我不知道什么是测试),但是当您调用 NgOnChanges 时,branchUserRole 的值被覆盖,或者您收到错误,因为服务未初始化。


推荐阅读