Spy on the result of an Observable Subscription with Jasmine

前端 未结 3 909
粉色の甜心
粉色の甜心 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:38

    Did you ever come up with a solution? What about using the jasmine-marbles package and the complete event?

    it('should update chart on new data', () => {
        const obs$ = cold('--a-|');
        spyOn(service, 'getCellOEE').and.returnValue(obs$);
        component.ngOnInit(); 
        obs$.subscribe({
            complete: () => {
                expect(component.updateChart).toHaveBeenCalledWith('a');
            }
        });
    });
    
    0 讨论(0)
  • 2021-01-24 13:45

    Instead of

    spyOn(service, 'getCellOEE').and.returnValue({ subscribe: () => { } });
    

    You could try

    spyOn(service, 'getCellOEE').and.returnValue( {subscribe: (callback) => callback()});
    
    0 讨论(0)
  • 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();
      });
    
    0 讨论(0)
提交回复
热议问题