在订阅后测试Angular 5单元测试中的错误

时间:2018-04-23 19:16:48

标签: angular unit-testing typescript karma-jasmine karma-coverage

我的Angular 5控制器中有以下功能,我想使用karma进行UnitTesting。

this.search.getFirstSearch().subscribe(data => {
      this.processSchool = data.search3,
        error =><any> this.errorMessage,
        ()=>{
          if(this.errorMessage ===''){
    console.log('abc')
          }else{
            console.log('xxxx')
          }
        }

    });

不幸的是,我在测试函数错误语句时遇到了困难。我尝试了以下代码,但据我所知,从生成的covrage中可以看出这部分内容。

it('should simulate error 1  ', () => {
    fixture.detectChanges();

    const searchService = fixture.debugElement.injector.get(SearchService);
    const mockCall= spyOn(searchService, 'getFirstSearch').and.returnValue(Observable.throw({status: 404}));

    //call method 
    comp.processData();

  });

  it('should simulate error 2  ', () => {

    const searchService = fixture.debugElement.injector.get(SearchService);
    const mockCall= spyOn(searchService, 'getFirstSearch').and.returnValue(Observable.throw({message: ""}));

    //call method 
    comp.processData();
  });



  it('should simulate error 3 ', async(() => { fixture.detectChanges();
    const searchService = fixture.debugElement.injector.get(SearchService);
    let    error404 = {status: 404};
    backend.connections.subscribe((connection: MockConnection) => {
      connection.mockError(error404 as any as Error);
    });

    comp.processData();
  }));


  ////added test

  it('should simulate error 4 ', () => { fixture.detectChanges();

    const searchService = fixture.debugElement.injector.get(SearchService);
    const mockCall= spyOn(searchService, 'getFirstSearch').and.returnValue(
      new ErrorObservable('TwainService test failure'))

    comp.processData();


  });

  it('should simulate error 5', () => { fixture.detectChanges();

    const searchService = fixture.debugElement.injector.get(SearchService);
    const mockCall= spyOn(searchService, 'getFirstSearch').and.returnValue(Observable.throw({message: ""}));

    comp.processData();

  });

从生成的报告中,未涵盖错误部分。我错过了什么?

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以尝试使用.and.throwError,如herehere所述。

spyOn(searchService, 'getFirstSearch').and.throwError({status: 404});

答案 1 :(得分:0)

根据你所拥有的,我认为你可能有无关的花括号包装传递给subscribe方法的参数。 subscribe signature.subscribe([onNext], [onError], [onCompleted])。否则,您已设置了分配给无变量的方法,并且永远不会运行(因此,为什么它说代码永远不会运行)。

this.search.getFirstSearch().subscribe(
  data => this.processSchool = data.search3, // onNext
  error => this.errorMessage = error,  // onError
  () => { // onCompleted
    if(this.errorMessage === '') {
      console.log('abc')
    } else {
      console.log('xxxx')
    }
  }
);