gpt4 book ai didi

angular - 如何在 Angular 中测试 mat-checkbox 的绑定(bind)?

转载 作者:行者123 更新时间:2023-12-04 02:57:48 25 4
gpt4 key购买 nike

我有一个 Angular 6 应用程序,想测试一个 mat-checkbox 的绑定(bind)是否有效。我有这个模板:

<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);
}));
});

我希望测试能够通过,但都失败并显示消息“预期未定义为真”。

我做错了什么?

提前致谢!

最佳答案

似乎句柄在复选框的标签中:

const checkBoxElement: HTMLElement = fixture.debugElement.query(By.css('#singleCheckBox label')).nativeElement;

来源: Angular Material 2 - Trigger change event in md-checkbox in a Unit Test

关于angular - 如何在 Angular 中测试 mat-checkbox 的绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52111148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com