如何测试订阅的价值变化?

How to test value changes from a subscription?

组件执行 API 调用,然后更改变量,例如:

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

现在我想编写一个测试来检查 apiService.postStuff() 是否被调用并且 this.variable 最终为真。

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 
});

缺少什么?谢谢

我认为您不想 callThrough() 在这种情况下。尝试删除 and.callThrough() 并改用 .and.returnValue(of(true))

最后,fakeAsync()tick() 可能是无关紧要的,因为上述建议 returns 是一个可观察的值。