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
相关产品推荐
相关产品推荐

