Reputation: 1243
I have a checkbox which has a (change) functions which sets a variable 'isSelected' to the event.checked value of the change function. Now I tried to test it with the help of this question on stackoverflow. However, I feel like the (change) event is not triggered as the 'isSelected' does not change. I also tried to use spyOn on the function which is triggered after (change) but this still returns that the function was no called (current test). Maybe someone knows how to detect the change and what I am doing wrong. Here is my code:
import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-intents-checkbox',
templateUrl: 'intents-checkbox.component.html',
styleUrls: ['intents-checkbox.component.scss']
})
export class IntentsCheckboxComponent implements OnChanges {
@Input() intentId;
constructor() { }
public isSelected = false;
intentChecked(event, intentId): void {
this.isSelected = event.checked;
}
}
The html:
<md-checkbox [checked]="isSelected"
(change)="intentChecked($event, intentId)"
class="project-checkbox">
</md-checkbox>
And my test so far:
it('should call intentChecked on change checkbox', () => {
let de = fixture.debugElement.query(By.css('.project-checkbox'));
de.triggerEventHandler('click', {});
fixture.detectChanges();
expect(component.intentChecked).toHaveBeenCalled();
})
( So the outcome of the test rn is that it fails because intentChecked was not called as expected ).
Thanks!
Upvotes: 2
Views: 8543
Reputation: 214175
I can offer you two options:
1) Trigger change
event on md-checkbox
element
it('should call intentChecked on change checkbox', () => {
let de = fixture.debugElement.query(By.css('.project-checkbox'));
spyOn(component, 'intentChecked');
de.triggerEventHandler('change', {});
expect(component.intentChecked).toHaveBeenCalled();
})
2) Trigger click
event on inner label
element
it('should call intentChecked on change checkbox', () => {
let de = fixture.debugElement.query(By.css('.project-checkbox label'));
let el = de.nativeElement;
spyOn(component, 'intentChecked');
el.click();
expect(component.intentChecked).toHaveBeenCalled();
})
As we want to check if intentChecked
method was called we need to spy on this method in both cases.
Upvotes: 12