Home > Back-end >  Karma-jasmine How i test a close function in a modal
Karma-jasmine How i test a close function in a modal

Time:01-21

I need to test this, but I'm new testing and I do not have idea, I'm working with angular, I just want to test the close function and maybe if it renders.

This is the html.

<div  *ngIf="active" id="modal">
    <div  role="document">
      <div >
        <div >
          <h1 >{{tittle}}</h1>
          <button type="button"  (click)="close()">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div >
          <ng-content select="[modal-body]"></ng-content>
          <div modal-body>
            <h5 >{{description}}</h5>
          </div>
        </div>
        <div >
          <ng-content select="[modal-footer]"></ng-content>
          <button type="button"  (click)="close()">Close</button>
        </div>
      </div>
    </div>
    <div  (click)="close()"></div>
  </div>

And this is the modal.component.ts


import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent {

  @Input() tittle: string = ''
  @Input() description: string = ''
  @Input() active: boolean = false;
  @Output() activeChange = new EventEmitter<boolean>();

  close() {
    this.active = false;
    this.activeChange.emit(this.active);
  }
}

CodePudding user response:

In order to test if EventEmitter emits an event when clicking on background div, you should write a test using spyOn like this:

it('should emit event for closing a modal on click event on background div', () => {
        spyOn(component.activeChange, 'emit');

        component.close();

        expect(component.activeChange.emit).toHaveBeenCalled();
    });

Make sure you have access to component, by having these lines in beforeEach block:

beforeEach(() => {
    fixture = TestBed.createComponent(ModalComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();
});
  •  Tags:  
  • Related