简体   繁体   English

Karma-jasmine 我如何在模态中测试关闭的 function

[英]Karma-jasmine How i test a close function in a modal

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.我需要对此进行测试,但我是新测试,我不知道,我正在使用 angular,我只想测试关闭的 function,也许它是否呈现。

This is the html.这是 html。

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

And this is the modal.component.ts这是 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);
  }
}

In order to test if EventEmitter emits an event when clicking on background div , you should write a test using spyOn like this:为了测试EventEmitter在单击背景div时是否发出事件,您应该使用spyOn编写一个测试,如下所示:

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块中包含这些行,确保您可以访问component

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

    fixture.detectChanges();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM