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.
JavaScript
x
25
25
1
<div class="modal active" *ngIf="active" id="modal">
2
<div class="modal-dialog modal-lg" role="document">
3
<div class="modal-content">
4
<div class="modal-header">
5
<h1 class="modal-title">{{tittle}}</h1>
6
<button type="button" class="close" (click)="close()">
7
<span aria-hidden="true">×</span>
8
</button>
9
</div>
10
<div class="modal-body">
11
<ng-content select="[modal-body]"></ng-content>
12
<div modal-body>
13
<h5 class="modal-description">{{description}}</h5>
14
</div>
15
</div>
16
<div class="modal-footer">
17
<ng-content select="[modal-footer]"></ng-content>
18
<button type="button" class="btn btn-secondary" (click)="close()">Close</button>
19
</div>
20
</div>
21
</div>
22
<div class="modal-background" (click)="close()"></div>
23
</div>
24
25
And this is the modal.component.ts
JavaScript
1
21
21
1
import { Component, Input, Output, EventEmitter } from '@angular/core';
2
3
@Component({
4
selector: 'app-modal',
5
templateUrl: './modal.component.html',
6
styleUrls: ['./modal.component.css']
7
})
8
export class ModalComponent {
9
10
@Input() tittle: string = ''
11
@Input() description: string = ''
12
@Input() active: boolean = false;
13
@Output() activeChange = new EventEmitter<boolean>();
14
15
close() {
16
this.active = false;
17
this.activeChange.emit(this.active);
18
}
19
}
20
21
Advertisement
Answer
In order to test if EventEmitter
emits an event when clicking on background div
, you should write a test using spyOn
like this:
JavaScript
1
8
1
it('should emit event for closing a modal on click event on background div', () => {
2
spyOn(component.activeChange, 'emit');
3
4
component.close();
5
6
expect(component.activeChange.emit).toHaveBeenCalled();
7
});
8
Make sure you have access to component
, by having these lines in beforeEach
block:
JavaScript
1
7
1
beforeEach(() => {
2
fixture = TestBed.createComponent(ModalComponent);
3
component = fixture.componentInstance;
4
5
fixture.detectChanges();
6
});
7