如果功能单元测试中未涵盖的陈述 - Jasmine

问题描述 投票:0回答:2

我正在为某个代码编写茉莉花测试用例。我已经介绍了组件中的函数,但函数中的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);
});
angular typescript karma-jasmine
2个回答
1
投票

需要在调用branchuserRole之前设置datangOnChanges

it('should set the value of data', () => {
    const changes: any = '';
    component.branchuserRole = TEST;
    component.data= []; // should not be null
    component.ngOnChanges(changes);
    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);
});

1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.