【问题标题】:Isolated testing: how to test callback of an Observable隔离测试:如何测试 Observable 的回调
【发布时间】:2019-07-26 09:57:46
【问题描述】:

我有一个组件,它使用服务打开一个模式对话框,用户可以在其中选择两个选项 {true, false} 之一。我想编写独立的测试(不创建测试平台)。我的问题是,回调根本没有被执行(测试失败,因为动作没有被调度)。

如何测试回调内部的行为?

bla.component.ts
    onCancelClicked(): void {
    this.unsavedChangesService.openUnsavedChangesModal().subscribe((leaveWithoutSaving: boolean) => {

            if (leaveWithoutSaving) {
                if (!this.savedChangesExisting()) {
                  this.store.dispatch(new DeleteDraft(this.id));
                } else {
                  this.store.dispatch(new ResetUnsavedChanges());
                }
                this.store.dispatch(new DeactivateEditMode());
              }
        });
    }
  }

    let unsavedChangesServiceMock: any  = {
      openUnsavedChangesModal: jasmine.createSpy().and.returnValue({
        subscribe: jasmine.createSpy().and.returnValue(of(true))
      })
    };


....

it('bla', () => {
      const expectedDeactivateEditModeAction: any = new DeactivateEditMode();

      sut['unsavedChanges'] = {[1]: 'something' };
      sut['draftsOfTTB'] = undefined;

      sut.onCancelClicked();

      expect(sut.store.dispatch).toHaveBeenCalledWith(expectedDeactivateEditModeAction);
}
....

【问题讨论】:

    标签: angular testing observable


    【解决方案1】:

    您有异步代码,因此您需要使用异步代码测试,如此处所述https://codecraft.tv/courses/angular/unit-testing/asynchronous/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      相关资源
      最近更新 更多