I'm trying to test a component with a checkbox but I can't find a solution to test checkbox-change event.
Here is my component to be tested:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-useparent-checkbox',
template: `
<input
type="checkbox"
(change)="changeChecked($event.currentTarget.checked)">`
})
export class UseparentCheckboxComponent {
@Output() toggle = new EventEmitter<boolean>();
changeChecked(isChecked: boolean) {
this.toggle.emit(isChecked);
}
}
and here is the test code:
let comp: UseparentCheckboxComponent;
let fixture: ComponentFixture<UseparentCheckboxComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ FormsModule ],
declarations: [
UseparentCheckboxComponent
],
});
fixture = TestBed.createComponent(UseparentCheckboxComponent);
comp = fixture.componentInstance;
});
it ('should send true when selected', fakeAsync(() => {
const inputDe = fixture.debugElement.query(By.css('input'));
const inputEl = inputDe.nativeElement;
expect(inputEl.checked).toBeFalsy();
let result;
comp.toggle.subscribe((res: boolean) => {
console.log('result', res);
result = res;
});
inputDe.triggerEventHandler('change', new Event('change'));
tick();
expect(result).toBe(true);
}));
And I have this error: "Cannot read property 'checked' of null". It looks like the problem is in "$event.currentTarget.checked": My new Event('change') has no target or currentTarget value.
If I change the event to click I got the same issue. I could change my component code to get the checkbox value not from the event but with a viewChild or somthing like that but I think the current code is better.
Does anyone have a solution? thanks!