【问题标题】:How to test if subscriber is called in angular?如何测试订阅者是否以角度调用?
【发布时间】:2020-02-12 12:45:46
【问题描述】:

我有一个组件订阅了由服务创建的全局扇出,我希望测试扇出是否确实被正确接收。所以,看看下面的代码,我想测试一下是否在 TestableComponent 中调用了 eventStartFanout$。

我知道代码实际上是通过“手动测试”来工作的 = 用我的眼睛,但我不知道如何将其转换为自动化测试。

我当前问题的最小化示例;

服务:

eventStartSubject = new Subject<any>();
eventStartFanout$ = this.eventStartSubject.asObservable();
function startEvent() {
  this.eventStartSubject.next();
}

可测试组件:

ngOnInit() {
  this.unchanged = true;
  this.fanoutService.eventStartFanout$.subscribe(
    _ => {
      // Test that it reaches here when service triggers
      this.changeVariable();
    }
  );
}

// Extra (unneeded) function to potentially help testing
function changeVariable(){
  this.unchanged = false;
}

我目前的测试尝试:

beforeEach(() => {
    fixture = TestBed.createComponent(TestableComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

it('should do something when fanout happens', async(() => {
    const fanoutService: FanoutService = TestBed.get(FanoutService);
    component.unchanged = true;
    spyOn(component, 'changeVariable');
    // It should trigger the subscriber here and change component.unchanged
    fanoutService.startEvent();
    fixture.detectChanges();
    expect(component.unchanged).toBeFalsy();
  }));

【问题讨论】:

    标签: angular testing jasmine karma-runner subscriber


    【解决方案1】:

    这比我想象的要简单。解决方案是使用fakeAsync 和tick() 来模拟订阅者可以执行更改的时间步,请参阅:

    it('should do something when fanout happens', fakeAsync(() => {
        const fanoutService: FanoutService = TestBed.get(FanoutService);
        component.unchanged = true;
        fanoutService.startEvent();
        tick();
        fixture.detectChanges();
        expect(component.unchanged).toBeFalsy();
      }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 2018-12-13
      • 2016-12-31
      • 2020-11-03
      相关资源
      最近更新 更多