Search code examples
javascripttypescriptjestjsts-jest

Best way to test a function that returns an observable operator


Best way to test a function that returns an observable with tap operator.

operations(numbers): Observable{
  const sumValue = numbers[0]+numbers[1]
  return sumService.getOperations(sumValue).pipe(tap(randomOperationValue => {this.value =    randomOperationValue}
))
}

I do not see how to test the value inside tap. I tried to mock getOperations() but without success.


Solution

  • A quick something should get you started

    describe('AppComponent', () => {
      let svc: OperationsService;
      let fixture: ComponentFixture<AppComponent>;
      let component: AppComponent;
    
      beforeEach(async () => {
        TestBed.configureTestingModule({
          declarations: [AppComponent],
          providers: [{
            provide: OperationsService,
            useValue: {
              getOperations: () => of(1000),
            }
          }]
        });
    
        svc = TestBed.inject(OperationsService);
        fixture = TestBed.createComponent(AppComponent);
        component = fixture.componentInstance;
      });
    
      it('should ...', fakeAsync(() => {
        const spy = jest.spyOn(svc, 'getOperations');
        const obs$ = component.operations([100, 200]);
    
        obs$.subscribe();
        tick();
    
        expect(spy).toHaveBeenCalledWith(300);
        expect(component.value).toBe(1000); // this is the fixed value we mock ^
      }));
    });