You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular Jasmine测试中获取mat-checkbox的选中值?

问题:Angular Material复选框测试中checked值始终为undefined

我想编写测试用例,验证当item.done为true时mat-checkbox是否处于选中状态。但在Jasmine测试中尝试获取该复选框的checked值时,结果始终为undefined,请问哪里操作有误?

我的Material复选框定义如下(功能正常):

<mat-checkbox id=checkbox [checked]="item.done" (change)="toggle(item)"  color="primary">...</mat-checkbox>

测试代码如下:

it( 'checkbox should be checked when done is true', fakeAsync(() => {
   component.item.done = true
   fixture.detectChanges()
   const checkbox = fixture.debugElement.nativeElement.querySelector('mat-checkbox')
   console.log(checkbox.checked)
   expect(checkbox.checked).toBeTruthy()
}));

console.log(checkbox)的返回结果为:

<mat-checkbox _ngcontent-a-c116="" id="checkbox" color="primary" class="mat-checkbox mat-primary" ng-reflect-id="checkbox" ng-reflect-color="primary" ng-reflect-checked="true">...</mat-checkbox>

解决方法

你遇到的问题是因为mat-checkbox是Angular Material封装的自定义组件,它的原生DOM元素并没有checked属性,你直接访问的是组件的外壳元素,而非实际负责状态的原生复选框元素。

这里提供两种可行的解决方式:

方式1:获取内部原生input元素

Angular Material的mat-checkbox组件内部会渲染一个原生的<input type="checkbox">,你可以直接定位这个元素来获取checked状态:

it( 'checkbox should be checked when done is true', fakeAsync(() => {
   component.item.done = true
   fixture.detectChanges()
   // 定位到mat-checkbox内部的原生input
   const checkboxInput = fixture.debugElement.nativeElement.querySelector('mat-checkbox input')
   expect(checkboxInput.checked).toBeTruthy()
}));

方式2:获取MatCheckbox组件实例

通过Angular的测试工具获取组件实例,直接访问其checked属性:

// 记得先导入By和MatCheckbox
import { By } from '@angular/platform-browser';
import { MatCheckbox } from '@angular/material/checkbox';

it( 'checkbox should be checked when done is true', fakeAsync(() => {
   component.item.done = true
   fixture.detectChanges()
   // 获取MatCheckbox组件实例
   const checkboxComponent = fixture.debugElement.query(By.directive(MatCheckbox)).componentInstance;
   expect(checkboxComponent.checked).toBe(true);
}));

另外你看到的ng-reflect-checked是Angular的调试属性,仅用于开发阶段查看绑定值,不能作为测试判断的依据。

内容的提问来源于stack exchange,提问作者restarcik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 21:30:53