JockelzF
JockelzF

Reputation: 433

How to test value changes from a subscription?

A component does an API call which then changes a variable, like:

postStuff() {
  this.apiService.postStuff(whatever).subscribe(
    res => {
      this.variable = true; // was previously false
  });
}

Now I want to write a test that checks if apiService.postStuff() was called and this.variable ends up as true.

it('should ...', fakeAsync(() => {
  spyOn(apiService, 'postStuff').and.callThrough();
  component.postStuff();
  expect(apiService.postStuff).toHaveBeenCalled(); // Works
  // tick(); // Does not seem to help
  expect(component.variable).toBeTrue(); // Does not work. Says it's still false 
});

What is missing? Thanks.

Upvotes: 1

Views: 1330

Answers (1)

furnace915
furnace915

Reputation: 68

I don't think you want to callThrough() in this scenario. Try removing and.callThrough() and using .and.returnValue(of(true)) instead.

Lastly, the fakeAsync() and tick() may be extraneous since the above suggestion returns an observable value.

Upvotes: 1

Related Questions