angular - 当我在 jasmine 单元测试中更改其模型时,mat-checkbox 不会更新检查状态
问题描述
我为材料复选框编写了一个单元测试。我使用 [(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>
解决方案
您很可能需要对 DOM/HTML 的新引用。checkbox
指fixture.detectChanges()
.
试试这个:
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(() => {
const newCheckbox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement; // grab new reference
expect(newCheckbox.checked).toBeTrue();
done();
});
});
推荐阅读
- python - 使用 Python 从 Google 表格中提取插入的图像
- python - python中每个第一个真值的索引
- database - 在 select 语句中选择一个计数的总和,其中日期介于
- java - 编译器如何引用自己的输出
- java - Maven项目Jenkins编译报错:错误:包org.apache.commons不存在
- sql-server - 找不到列“dbo”或用户定义的函数或聚合“TryConvertInt”,或者名称不明确
- python - 使用 itemgetter 或比 lambda 更快的方法按元组第 n 个元素对嵌套元组列表进行排序
- postman - 一个变量的当前值可以用作 Postman 中另一个变量的 Key 吗?
- raspberry-pi - 我们如何通过键盘在树莓派中选择 wifi
- java - 错误的屏幕宽度返回 javaFX