Angular v15中Getter函数单元测试遇阻:无法Mock Firestore
解决Angular v15中Firestore Getter函数单元测试的Mock问题
你的测试报错是因为AngularFire的collection()方法需要符合其内部结构的Firestore实例,而你当前的mock只是一个jest函数,无法通过AngularFire的校验,触发了模块未提供的错误。
问题核心
collection(this._fireStore, this.year.toString())调用的是AngularFire导出的工具函数,它依赖的Firestore实例是AngularFire封装后的对象,不是简单的mock函数就能替代的。
修正方案
直接mock AngularFire的collection函数,而非仅mock Firestore实例,步骤如下:
- 在测试文件顶部mock
collection函数
import { collection } from '@angular/fire/firestore'; // 保留AngularFire其他原有实现,仅mock collection方法 jest.mock('@angular/fire/firestore', () => ({ ...jest.requireActual('@angular/fire/firestore'), collection: jest.fn(), }));
- 简化Firestore实例的mock
不需要复杂的spy,提供一个空对象即可满足注入需求:
let dataService: DataService; const mockFirestore = {} as Firestore; beforeEach(() => { TestBed.configureTestingModule({ providers: [ DataService, { provide: Firestore, useValue: mockFirestore } ], }); dataService = TestBed.inject(DataService); });
- 编写正确的测试用例
预设collection的返回值,验证调用参数和返回结果:
describe('collection get()', () => { it('should return a Firestore collection with the correct name', () => { const mockCollectionRef = { valueChanges: jest.fn() }; // 类型断言告诉jest这是mock函数 (collection as jest.Mock).mockReturnValue(mockCollectionRef); const result = dataService.collection; // 验证collection是否用正确参数调用 expect(collection).toHaveBeenCalledWith(mockFirestore, '2023'); // 验证返回值是否符合预期 expect(result).toEqual(mockCollectionRef); }); });
为什么这样有效
通过直接mock AngularFire的collection工具函数,我们绕过了其内部对Firestore实例的校验逻辑,同时能精准验证Getter是否按预期调用了collection方法,传入了正确的集合名称。
内容的提问来源于stack exchange,提问作者Mr A
相关产品推荐
相关产品推荐

