我有一个Angular 6应用程序,想测试mat-checkbox的绑定是否有效。我有这个模板:
<div style="text-align:center">
<mat-checkbox id="singleCheckBox" [(ngModel)]="isChecked">Check me!</mat-checkbox>
</div>
和此代码:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
isChecked: boolean;
}
我用以下代码对其进行测试:
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);
}));
});
我希望测试能够通过,但是都失败,并显示消息“ Expected undefined is true”。
我在做什么错?
谢谢!
答案 0 :(得分:1)
似乎手柄在复选框的标签中:
const checkBoxElement: HTMLElement = fixture.debugElement.query(By.css('#singleCheckBox label')).nativeElement;
来源:Angular Material 2 - Trigger change event in md-checkbox in a Unit Test