angularunit-testingjasminengx-bootstrap-modal

Angular Unit Test: Access template variable


I have this code in a component template, which opens a ngx-bootstrap modal:

<button type="button"
        class="btn btn-primary"
        (click)="onOpenSharesModal(modal)">Click me!</button>
<ng-template #modal>
    <app-modal (closed)="onCloseSharesModal()"></app-modal>
</ng-template>

Component:

onOpenSharesModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template, { class: 'modal-lg' });
}

Test:

it('should call onOpenSharesModal() when button clicked', () => {
  const button = fixture.debugElement.query(By.css('button'));
  const spy = spyOn(component, 'onOpenSharesModal');

  button.triggerEventHandler('click', null);
  fixture.detectChanges();

  expect(spy).toHaveBeenCalled();
});

I'm trying to test the component: I've been able to test that onOpenSharesModal() is being called, but I'd like to test if it was called with the modal template variable as argument. How can I do that?


Solution

  • You can use a spy to spy on the function and check what was passed as an argument. Let's assume your component is called MyComponent. In your unit test file you have (a bit shortened, but you should get the picture):

    let myComponent: MyComponent = fixture.componentInstance;
    
    // Set up a spy on your function
    let spy = spyOn(myComponent, 'onOpenSharesModal').and.callThrough();
    
    // After the function has been called somewhere in your component
    expect(spy).toHaveBeenCalled();
    
    // Check the arguments that were passed
    expect(spy.calls.mostRecent().args[0]).toEqual(myComponent.modal);
    

    This is assuming the modal template variable is accessible from your component.