Spy on the result of an Observable Subscription with Jasmine

前端 未结 3 956
粉色の甜心
粉色の甜心 2021-01-24 13:22

I am Jasmine unit testing an angular component, which uses Observables. My component has this lifecycle hook that I am testing:

ngOnInit() {
  this.dataService.ge         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-24 13:59

    Not sure if this is the best way to do it, but I've seen it working on a project I'm working on. The approach is basically get a reference to the callback function provided to the subscribe method, and call it manually to simulate the observer emitting a value:

    it('should update chart on new data', () => {
        component.ngOnInit();
    
        // this is your mocked observable
        const obsObject = service.getCellOEE.calls.mostRecent().returnValue;
    
        // expect(obsObject.subscribe).toHaveBeenCalled() should pass
    
        // get the subscribe callback function you provided in your component code
        const subscribeCb = obsObject.subscribe.calls.mostRecent().args[0];
    
        // now manually call that callback, you can provide an argument here to mock the "value" returned by the service
        subscribeCb(); 
    
        expect(component.updateChart).toHaveBeenCalled();
      });
    

提交回复
热议问题