Angular+Jest+Firebase测试AppComponent报NullInjectorError如何解决
问题修复方案
错误原因说明
你遇到的两个错误分别对应两个根因:
- 第一个
NullInjectorError是因为你的AppComponent依赖的GuiSecurityAuthService间接依赖AngularFireAuth,测试模块中没有提供Firebase配置对应的注入令牌,所以找不到依赖。 - 第二个
INTERNAL ASSERTION FAILED: Expected a class definition是@angular/fire v7+和Jest默认配置不兼容导致的,@angular/fire v7采用ES模块格式输出Ivy编译产物,Jest默认不会转换node_modules下的ES模块,导致编译识别失败。 - 加Node环境注释的方案不适用浏览器端项目,Node运行时没有
window全局对象,必然会触发ReferenceError。
推荐解决方案(单元测试最佳实践)
单元测试不需要接入真实的Firebase服务,直接Mock上层的GuiSecurityAuthService即可,完全避开底层Firebase依赖问题:
describe('AppComponent', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ RouterTestingModule, ], declarations: [AppComponent], // 新增Mock依赖的服务 providers: [ { provide: GuiSecurityAuthService, useValue: { // 这里补充组件调用的所有GuiSecurityAuthService方法的Mock实现 // 示例:如果组件调用了getCurrentUser方法,就写 // getCurrentUser: jest.fn(() => of({ uid: 'test-uid' })) } } ] }).compileComponents(); }); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app).toBeTruthy(); }); });
备选方案(必须使用真实AngularFire的场景)
如果你的测试逻辑必须依赖真实的AngularFire能力,按以下步骤修改:
- 修改Jest配置(
jest.config.js或者项目根目录的jest.preset.js),添加@angular/fire相关包到转换白名单:
module.exports = { // 其他原有配置不变 transformIgnorePatterns: [ 'node_modules/(?!.*\\.mjs$|@angular/fire|rxfire|firebase)' ] }
- 修改测试模块配置,直接提供Firebase配置令牌,不需要完整导入
AngularFireModule:
import { FIREBASE_OPTIONS } from '@angular/fire/compat'; describe('AppComponent', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ RouterTestingModule, ], declarations: [AppComponent], providers: [ // 直接提供Firebase配置令牌 { provide: FIREBASE_OPTIONS, useValue: environment.firebaseConfig } ] }).compileComponents(); }); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app).toBeTruthy(); }); });
内容的提问来源于stack exchange,提问作者code
相关产品推荐
相关产品推荐

