2

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!

1 Answer 1

4

Check bellow code this will helps..

it ('should send true when selected', fakeAsync(() => {

const compiled = fixture.debugElement.nativeElement;
const elem = compiled.querySelector('#revert-project');

expect(elem.checked).toBeFalsy();
elem.change(); //or you can use click();
expect(elem.checked).toBe(true);
}));
Sign up to request clarification or add additional context in comments.

1 Comment

This does not update the model (component). It still has old values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.