【发布时间】:2020-09-22 09:11:32
【问题描述】:
我为材料复选框编写了一个单元测试。我使用 [(ngModule)] 将复选框绑定到模型。第一个测试用例没问题,单击复选框将更新模型但是当我在下一个单元测试中更改模型时,它不会发生。换句话说,当我将 enable 设置为 true 时,checked 状态不会更改为 true! 如何通过最后的单元测试? 代码上传到github
@Component({
selector: 'app-checkbox',
templateUrl: './checkbox.component.html'
})
export class CheckboxComponent implements OnInit {
enabled = false;
constructor() { }
ngOnInit(): void {
}
}
describe('CheckboxComponent', () => {
let component: CheckboxComponent;
let fixture: ComponentFixture<CheckboxComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CheckboxComponent ],
imports: [
MatCheckboxModule,
BrowserAnimationsModule,
BrowserModule,
FormsModule
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CheckboxComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('click checkbox changes enabled', () => {
const checkBox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
expect(component.enabled).toBeFalse();
checkBox.click();
expect(component.enabled).toBeTruthy();
});
it('changing enabled will alter checkbox state', (done) => {
const checkBox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
component.enabled = true;
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(checkBox.checked).toBeTrue();
done();
});
});
});
<mat-checkbox [(ngModel)]="enabled">Check me!</mat-checkbox>
【问题讨论】:
标签: angular unit-testing angular-material jasmine