1

I try to change checkbox checked property by changing model but it doesn't work. I cannot understand this behavior.

Template:

<input type="checkbox" [(ngModel)]="model"/>

Testing Code:

    it('should be checked after click on unchecked checkbox', () => {
        const checkbox: HTMLInputElement = fixture.nativeElement.querySelector('input');

        component.model = true;
        fixture.detectChanges();
        expect(checkbox.checked).toBeTruthy();
    });

Full code: https://stackblitz.com/edit/angular-testing-checkbox?file=app/app.component.spec.ts

2 Answers 2

3

Because angular change detection is asynchronous. Your expect() statement is executed before detectChanges(). Use angular testing async() function for this case:

   it('should be checked after click on unchecked checkbox', async( () => {
        const checkbox: HTMLInputElement = fixture.nativeElement.querySelector('input');    
        component.model = true;
        fixture.detectChanges();    
        fixture.whenStable().then(()=> {
          expect(checkbox.checked).toBeTruthy();
        })   
    }));
Sign up to request clarification or add additional context in comments.

Comments

1

You could use fixture.whenStable together with the done function to synchronize the asynchronous change detection cycle with the expect.

it('should be checked after click on unchecked checkbox', (done) => {
    const checkbox: HTMLInputElement = fixture.nativeElement.querySelector('input');

    component.model = true;
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(checkbox.checked).toBe(true);
      done();
    });
});

Comments

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.