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

Angular单元测试报错:Cannot read properties of null(滑动切换组件测试)

解决Angular mat-slide-toggle单元测试「Cannot read properties of null」错误

错误原因

  • 设置component.checked = true后未触发变更检测,*ngIf控制的DOM元素未渲染,导致querySelector返回null
  • 错误调用togtext.nativeElement:querySelector已返回DOM元素(HTMLElement类型),该类型不存在nativeElement属性

修复后的测试用例

it('load slide text', () => {
  component.checked = true;
  fixture.detectChanges(); // 触发变更检测,渲染*ngIf内的DOM结构
  const togtext = fixture.debugElement.nativeElement.querySelector('mat-slide-toggle') as HTMLElement;
  expect(togtext.innerText).toContain('Toggle1'); // 直接访问元素的innerText
});

额外必要配置

确保测试模块中导入所需依赖,否则组件无法正常渲染:

import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { FormsModule } from '@angular/forms';

beforeEach(async () => {
  await TestBed.configureTestingModule({
    imports: [MatSlideToggleModule, FormsModule], // FormsModule支持ngModel双向绑定
    declarations: [YourComponent] // 替换为你的组件类名
  }).compileComponents();
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 22:05:17