Angular17+Angular Material执行ng test报NG05105错误求助
Angular 17 + Angular Material 测试报错 NG05105 解决方案
问题原因
执行ng test时触发的NG05105错误,是因为你用到的Angular Material组件(比如报错里的侧边栏MatSidenav)依赖Angular动画模块,但测试模块中未导入对应的动画处理模块,导致无法识别组件的动画监听事件。
解决方案
方案1:禁用动画(推荐用于测试,提升执行速度)
在组件的测试文件(通常是app.component.spec.ts)中导入NoopAnimationsModule,该模块会空实现动画逻辑,避免测试时处理动画相关逻辑:
import { TestBed } from '@angular/core/testing'; import { AppComponent } from './app.component'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { MatSidenavModule } from '@angular/material/sidenav'; // 导入你用到的Material组件模块 describe('AppComponent', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ NoopAnimationsModule, // 添加此行 MatSidenavModule ], declarations: [ AppComponent ], }).compileComponents(); }); // 你的测试用例... });
方案2:保留动画(适合需要测试动画行为的场景)
如果测试中需要验证动画效果,可导入BrowserAnimationsModule替代NoopAnimationsModule:
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; // ... imports: [ BrowserAnimationsModule, // 替换成这个模块 MatSidenavModule ], // ...
额外提示
如果多个测试模块都需要处理动画,也可以在test.ts文件中全局导入动画模块,但更建议在单个测试模块中按需导入,保持测试的独立性和隔离性。
内容的提问来源于stack exchange,提问作者Jan Nielsen
相关产品推荐
相关产品推荐

