Angular 12单元测试:如何获取mat-select的选中值或文本
Angular 12单元测试:如何获取mat-select的选中值或文本
嗨,我完全懂你碰到的这个坑——普通input可以直接通过nativeElement.value拿到值,但mat-select因为是Angular Material封装的组件,DOM结构和原生input不一样,直接这么取自然会返回undefined。给你几个实用的解决办法:
方法一:直接访问FormControl的value(最推荐)
既然你的mat-select已经绑定了formControlName="genderType",那最直接的方式就是直接从组件的表单控件里拿值,不用绕DOM:
// 假设你的组件里定义了对应的FormGroup,比如叫userForm const genderControl = component.userForm.get('genderType'); expect(genderControl.value).toBe(1);
这种方式更符合Angular表单的设计思路,也不用依赖DOM结构的变化,稳定性更高。
方法二:通过MatSelect组件实例获取
你可以拿到mat-select的组件实例,直接访问它的value或者selectedOption属性:
import { MatSelect } from '@angular/material/select'; // 获取mat-select的DebugElement,再拿到组件实例 const matSelect = findEl(fixture, "genderType").componentInstance as MatSelect; // 断言选中值 expect(matSelect.value).toBe(1); // 如果需要断言显示的文本(比如gender.name) expect(matSelect.selectedOption?.viewValue).toBe('女性'); // 替换成你对应的选项文本
方法三:通过DOM查询选中的mat-option
如果一定要从DOM层面获取,可以找到被标记为selected的mat-option元素,再取它的值或文本:
import { By } from '@angular/platform-browser'; const matSelectEl = findEl(fixture, "genderType"); // 找到选中的option const selectedOption = matSelectEl.query(By.css('mat-option[selected]')); // 断言选中值 expect(selectedOption.nativeElement.value).toBe(1); // 断言显示的文本 expect(selectedOption.nativeElement.textContent.trim()).toBe('男性');
为什么之前的方法不行?
简单说,mat-select的原生DOM元素是一个封装后的容器(比如div),它本身并没有value属性——真正的选中值是存在MatSelect组件实例里,或者绑定到对应的FormControl上的,所以直接取nativeElement.value自然会得到undefined啦。
备注:内容来源于stack exchange,提问作者Bianca Yameê
相关产品推荐
相关产品推荐

