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?
- products$ observable should emit all the four values
- third emitted data should be
prod3
New contributor
aagash is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
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');
}
You can test it using the rxjs operator toArray()
, which collects all the emits to an array.
it("should emit third value as 'prod3'", (done) => {
service.product$.pipe(toArray()).subscribe((data: any) => {
expect(data.length).toEqual(4);
expect(data[2]).toEqual('prod3');
done();
});
});