簡體   English   中英

訂閱后Angular 5單元測試中的測試錯誤

[英]Testing errors in Angular 5 Unit Testing after subscribtion

我的Angular 5控制器中具有以下功能,我想在該控制器上使用業力進行單元測試。

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

    });

不幸的是,我在測試函數錯誤語句時遇到困難。 我嘗試了以下代碼,但是據我所產生的變化,本部分沒有涉及。

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();

  });

從生成的報告中,未涵蓋錯誤部分。 我想念什么?

在此處輸入圖片說明

您可以嘗試使用.and.throwError,如此此處所述

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

根據您所擁有的內容,我認為您可能會有多余的花括號來包裝傳遞給訂閱方法的參數。 訂閱簽名.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')
    }
  }
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM