monxas
monxas

Reputation: 2637

testing subscribe in karma gives error Argument of type 'Observable<>' is not assignable to parameter of type 'Subscription'

I have this method

loadCombos(): void {
  this.combosService.accounts$.subscribe(
    (data: any) => {
    this.list = data;
      }
    }
  );
}

and this is my current test:

it('should test loadCombos executions ', (done) => {
  combosService = TestBed.inject(CombosService);
  spyOn(combosService.accounts$, 'subscribe').and.returnValue(of(mockList));
  component.loadCombos();
  expect(component.list).not.toBeNull();

  done();
});

how can I use mockList on my test, currently I'm getting that's an observable but it needs a suscription, but I don't know how to do it.

Upvotes: 0

Views: 1606

Answers (1)

distante
distante

Reputation: 7005

There are a couple of errors here.

One subscribe() does not return an Observable it returns a Subscription like the error says. You could return an new Subscription() in your test but that does not make any sense.

If you want to mock the return of your accounts$. The correct way is to change CombosService for a mocked implementation. Take a look at the documentation.

A fast way to test it will be to overwrite accounts directly (if it is not marked as readonly)


it('should test loadCombos executions ', (done) => {
  combosService = TestBed.inject(CombosService);
  combosService.accounts$ =  of(mockList);
  component.loadCombos();
  expect(component.list).not.toBeNull();

  done();
});

I would not do this though because if loadCombos() is called from somekind of button, that implementation is wrong.

Edit: Personally I like to test observables inside fakeAsync calls: https://angular.io/api/core/testing/fakeAsync

Upvotes: 2

Related Questions