使用单元测试在RxJS管道内执行逻辑

时间:2020-09-16 16:25:21

标签: angular unit-testing rxjs jasmine karma-jasmine

在进行单元测试时,尝试在pipe()方法内部初始化变量x,但不会被调用。如何在pipe()中运行方法调用/初始化逻辑?仅仅在单元测试中调用component.ngOnInit()并没有帮助。

ngOnInit() {
    this.foo$ = this.myService.bar$.pipe(
      ....
      map(bar => {
        this.x = bar.x;        // how do I call this within unit test 
        return bar;
      })
    );  
}

it('should init x', () => {
    component.ngOnInit();
    expect(component.x).toEqual(bar.x); //fails
});

1 个答案:

答案 0 :(得分:0)

您可能想订阅然后打勾

  import { fakeAsync, tick } from '@angular/core/testing'; 

  it('should init x', fakeAsync(() => {
    component.ngOnInit();
    component.foo$.subscribe();
    tick();
    expect(component.x).toEqual(bar.x); 
  }));