执行ng test时遇MsalModule无ɵmod属性错误,求解决方案
解决Angular测试中MsalModule无ɵmod属性的错误
执行
ng test时出现如下错误:MsalModule does not have a module def (ɵmod property) 36 | describe('AppComponent', () => { 37 | beforeEach(waitForAsync(() => { > 38 | TestBed.configureTestingModule({已尝试添加
import 'jest-preset-angular/setup-jest';,但错误仍存在。
以下是可行的解决方案:
模拟MsalModule而非直接引入
测试时不需要加载真实的MsalModule,用模拟模块替代:
如果使用ng-mocks库,可以直接用MockModule包裹:import { MockModule } from 'ng-mocks'; import { MsalModule } from '@azure/msal-angular'; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [MockModule(MsalModule)], // 其他组件、服务配置 }).compileComponents(); }));也可以手动创建空的模拟模块:
@NgModule({}) class MockMsalModule {} beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [MockMsalModule], // 其他配置 }).compileComponents(); }));校验版本兼容性
确认@azure/msal-angular版本与当前Angular版本匹配:- Angular 16+ 对应 Msal Angular v3.x
- Angular 12-15 对应 Msal Angular v2.x
版本不匹配会导致模块内部结构不兼容,出现ɵmod属性缺失问题。
完善Jest测试环境配置
除了在文件中导入jest-preset-angular/setup-jest,还要确保jest.config.js中正确配置preset:module.exports = { preset: 'jest-preset-angular', setupFilesAfterEnv: ['<rootDir>/src/setup-jest.ts'], // 其他Jest配置项 };同时保证
src/setup-jest.ts仅包含必要初始化代码,无冲突逻辑。清理缓存后重新测试
执行命令清理测试缓存,避免旧缓存导致的异常:ng test --clearCache
内容的提问来源于stack exchange,提问作者Akshay Jagtap
相关产品推荐
相关产品推荐

