首页 > 解决方案 > 模拟订阅变量

问题描述

我有一个名为 stateSubscition$ 的变量,我用它来保存和取消订阅订阅,它运行良好。但我需要知道如何模拟 stateSubscription$ 为 ondes 编写单元测试用例

stateSubscription$: Subscription;
...
this.stateSubscription$ = this.updatedScheduleActivities$.subscribe((x) => {
  this.loadGrid();
});
...
ngOnDestroy() {
  this.stateSubscription$.unsubscribe();
}

并在规范文件中

fdescribe('#onDestroy', () => {
    let component;
    beforeEach(() => {
      component = new VariableComponent(mockStore, mockForm);
      spyOnProperty(component,'stateSubscription$','get').and.returnValue(Observable);
      component.ngOnDestroy();
    });

    it('should have called unsubscribe method', () => {
        expect(component.stateSubscription$.unsubscribe).toHaveBeenCalled();
    });

  });

我收到这样的错误,如何模拟这个属性?

Error: stateSubscription$ property does not exist

标签: angularjasminekarma-jasmine

解决方案


你总是可以stateSubcription$用一个空来初始化Subscription

stateSubscription$ = new Subscription();

undefined这样您在访问该物业时就不必担心。


推荐阅读