I have to test below function
addAll($event: any) {
this.Deletion = [];
if ($event['srcElement']['checked']) {
this.Model.forEach(file => {
this.Deletion.push(file.docId);
});
}
}
This function add files in Deletion array if checkbox is checked
HTML is as below
<input type="checkbox" id="addAllCheckBox" (change)="addAll($event)">
Spec.ts file
it('should call addAll on checkbox change event', fakeAsync(() => {
const handleSpy = spyOn(component, 'addAll');
const myCheckBox = fixture.debugElement.query(By.css('#addAllCheckBox'));
tick();
fixture.whenStable().then(res => {
fixture.detectChanges();
myCheckBox.triggerEventHandler('change', { target: { checked: true } });
expect(handleSpy).toHaveBeenCalled();
});
}));
I am getting an ERROR
Error: Uncaught (in promise): TypeError: Cannot read properties of null (reading 'triggerEventHandler')
I created this testcase by taking below refereces from stackoverflow
Jasmine test for checkbox change handler function in angular 12
Angular: testing checkbox change event issue
I search on the internet for this issue but I did not understand why I m getting this error
How should I solve this issue?
You didn't show the full template but here are some recommendations anyway:
Check if your checkbox input is inside some *ngIf and it receives true at the time you're trying to access your checkbox via te query selector.
Remove fakeAsync and replace it with this:
it('should call addAll on checkbox change event', (done) => { ... });
detectChanges
before accessing the checkbox via the query selector (after zone is stabilized):fixture.detectChanges();
fixture.whenStable().then(() => {
const myCheckBox = fixture.debugElement.query(By.css('#addAllCheckBox'));
myCheckBox.triggerEventHandler('change', { target: { checked: true } });
expect(handleSpy).toHaveBeenCalled();
done();
});
Please, let me know if you succeeded in accessing the checkbox reference.