玩笑和Angular并监视ViewChild函数

时间:2019-09-24 16:10:40

标签: angular unit-testing testing jestjs

我正在使用Spectator,Jest和Angular,并且尝试测试是否正在调用@ViewChild函数。

我具有以下实现方式:

describe('CollectiveModalComponent', () => {
  const createComponent = createComponentFactory({
    component: CollectiveModalComponent,
    detectChanges: false,
    shallow: true
  });

 describe('when handling the event', () => {
    beforeEach(() => {
      spectator = createComponent();

      jest.spyOn(component.modal, 'close');
      spectator.detectChanges();
    });

    it('should also close the modal if shouldCloseModal is true in the event', () => {
      // Arrange
      const collective = event();

      // Act
      component.handleEvent({
        object: event,
        shouldCloseModal: true
      });

      // Assert
      expect(component.modal.close).toHaveBeenCalled();
    });
  });
});

这给了我以下错误:

Cannot spy the close property because it is not a function; undefined given instead

TypeError: this.modal.close is not a function

我的组件看起来像这样:

// left out imports
@Component({
  // left out
})
export class Custom Component implements OnInit, OnDestroy {
  @ViewChild('modal', { static: false }) modal;

  handleEvent(event: CusomtEvent) {
    this.selectedCollectiveEmmiter.emit(event.object);

    if (event.shouldCloseModal) {
      this._close();
    }
  }


  private _close() {
    this.modal.close();
  }
}

我知道我必须在该viewChild上创建一个间谍,但是我可以这样做吗?到目前为止,我已经研究过使用ng-mocks模拟viewchild组件,但是我不想使用该库,因为它使用了Jasmine,并且我不再希望对Jasmine有任何依赖。

如何解决此问题?

0 个答案:

没有答案