Reputation: 43
I have an Angular 6 application and would like to test that the binding of a mat-checkbox works. I have this template:
<div style="text-align:center">
<mat-checkbox id="singleCheckBox" [(ngModel)]="isChecked">Check me!</mat-checkbox>
</div>
and this code:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isChecked: boolean;
}
I test it with this code:
import { TestBed, async, tick, fakeAsync } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { MatCheckboxModule } from '@angular/material';
import { By } from '@angular/platform-browser';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
imports: [
FormsModule,
MatCheckboxModule,
],
}).compileComponents();
}));
it('should update the property if the checkbox is clicked (using whenStable)', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
const checkBoxElement: HTMLElement = fixture.debugElement.query(By.css('#singleCheckBox')).nativeElement;
checkBoxElement.click();
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(compiled.isChecked).toBe(true);
});
}));
it('should update the property if the checkbox is clicked (using fakeAsync)', fakeAsync(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
const checkBoxElement: HTMLElement = fixture.debugElement.query(By.css('#singleCheckBox')).nativeElement;
checkBoxElement.click();
tick();
fixture.detectChanges();
expect(compiled.isChecked).toBe(true);
}));
});
I would expect the tests to pass but both fail with the message "Expected undefined to be true."
What am I doind wrong?
Thanks in advance!
Upvotes: 4
Views: 6560
Reputation: 281
It seems the handle is in the label of the check box:
const checkBoxElement: HTMLElement = fixture.debugElement.query(By.css('#singleCheckBox label')).nativeElement;
Source: Angular Material 2 - Trigger change event in md-checkbox in a Unit Test
Upvotes: 5