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
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');
}
});
});
Instead of
spyOn(service, 'getCellOEE').and.returnValue({ subscribe: () => { } });
You could try
spyOn(service, 'getCellOEE').and.returnValue( {subscribe: (callback) => callback()});
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();
});