angularunit-testingrxjsjasminekarma-jasmine

How to test observable that emits multiple times on subscription in jasmine angular framework


I am having a service product.service.ts

class ProductService {

public product$: Observable<string> = from(['prod1','prod2','prod3','prod4']);

<other methods goes here...>

}

I want to test the below cases?

  1. products$ observable should emit all the four values
  2. third emitted data should be prod3

Solution

  • We can achieve this using jasmine.spy

    it('should emit respective products'){
        const productsSpy = jasmine.createSpy();
    
        service.products$.subscribe(productsSpy);
    
        expect(productsSpy).toHaveBeenCalledTimes(4);
        expect(productsSpy.calls.argsFor(2)[0]).toBe('prod3');
    
    }