5

我在编写组件方法的测试用例时遇到了问题。

如何测试内部和内部的 Angular 组件方法if else块。subscribe((res) => { ///block}ToasterService

我在 component.ts 文件中调用了 Angular 服务方法。在服务调用内subscribe(response=>{}

我已经验证了if else块中的响应值,并根据结果显示烤面包机消息,但我的业力报告说:response=> function not covered并且if else块内没有声明未涵盖。

组件.ts

constructor(private userService: UserService,
    private toastr: ToastrService) { }
sortUsers(sortKey: string) {
    this.userService.getSortUserList(sortKey).subscribe((res) => {
      if(res.Success){
        this.userService.users = res.Data as User[];
      }else{
        this.toastr.error(res.Message);
      }
      
    });
  }

组件.spec.ts

it('call sortUser when users are sorted', () => {
    const users: User[] = [{
      User_Id: 1,
      First_Name: 'Madhu Ranjan',
      Last_Name: 'Vannia Rajan',
      Employee_Id: 12345,
      Project_Id: 1,
      Task_Id:1,
      _id: 'xcv'
    }];

    component.sortUsers('First_Name');
    const res = {Success: true, Data: users}
    spyOn(service, 'getSortUserList').and.returnValue(of({Success: true, Data: users}));    
  });

期待下面的块也被茉莉花测试:

subscribe((res) => {
      if(res.Success){
        this.userService.users = res.Data as User[];
      }else{
        this.toastr.error(res.Message);
      }
      
    });

业力报告:

业力报告

4

1 回答 1

2

尝试

constructor(
    public userService: UserService,
    public toastr: ToastrService) { 
}

在规范文件中:

it('call sortUser when users are sorted with success', () => {
    const users: User[] = [{
      User_Id: 1,
      First_Name: 'Madhu Ranjan',
      Last_Name: 'Vannia Rajan',
      Employee_Id: 12345,
      Project_Id: 1,
      Task_Id:1,
      _id: 'xcv'
    }];    
    const res = {Success: true, Data: users}
    spyOn(component.userService, 'getSortUserList').and.returnValue(of(res));  
    spyOn(component.toastr,'error').and.callThrough();
    component.userService.users = undefined;
    component.sortUsers('First_Name');
    expect(component.userService.users).toBeDefined()   
    expect(component.toastr.error).not.toHaveBeenCalled()  
  });

it('call Error Toaster in sortUser() when users are sorted', () => {
    const res = {Message: 'error_msg'}
    spyOn(component.userService, 'getSortUserList').and.returnValue(of(res));  
    spyOn(component.toastr,'error').and.callThrough();
    component.userService.users = undefined;
    component.sortUsers('First_Name');
    expect(component.userService.users).not.toBeDefined()   
    expect(component.toastr.error).toHaveBeenCalledWith('error_msg')  
  });

由于您是新手,karama我强烈建议您阅读这篇文章,其中包含在底部页面处理 Angular 单元测试的文章集合。

于 2019-08-15T04:32:23.343 回答