mardi 24 septembre 2019

Jest and Angular and spying on ViewChild function

I am using Spectator, Jest and Angular and I am trying to test if a @ViewChild function is being called.

I have the following implementation:

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();
    });
  });
});

This gives me the following errors:

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

TypeError: this.modal.close is not a function

My component looks like this:

// 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();
  }
}

I know i have to create a spy on that viewChild but in way way can I do that? So far I've looked into mocking the viewchild component with ng-mocks, but I don't want to use that library because it uses Jasmine, and I don't want any dependencies anymore on Jasmine.

How can I solve this issue?

Aucun commentaire:

Enregistrer un commentaire