如何在创建组件时测试是否调用了函数

时间:2019-01-14 17:45:47

标签: angular6 angular-test angular-testing

我有一个Component,它在初始化期间向服务器发送一条消息以获取一些信息(在ngOnInit中)。如果服务器返回错误,则应调用特定功能。

ngOnInit(){

this.service.tags$.subscribe((result:Result)=>{
      ...
    },
      (err:Result)=>{
        ...
       this.showDialog(err.additionalInfo,new DialogContext("",""));// I WANT TO TEST THAT THIS FUNCTION IS CALLED IF SERVER RETURNS ERROR
          } 
      });
}

我想对该功能进行单元测试,但无法。问题似乎是在创建组件之后调用it。因此,监视showDialog无效。

    it('should show error if unable to get tags from the server on loading', () => {
        let myComponent = component;
        let service= TestBed.get(MyService);
        spyOn(myComponent,'showDialog');

//this expectation will not workk as the showDialog was called before it was executed  
        expect(newPracticeQuestionComponent.showDialog).toHaveBeenCalled();

      });

0 个答案:

没有答案