Search code examples
angularjasminekarma-jasmineangular16

Jasmine test case for checkbox event handler Angular 16, jasmine 4.3.5


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?


Solution

  • You didn't show the full template but here are some recommendations anyway:

    1. 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.

    2. Remove fakeAsync and replace it with this:

    it('should call addAll on checkbox change event', (done) => { ... });
    
    1. call 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.