Angular服务中window.performance.getEntriesByType的Jasmine Mock问题
解决Angular中Mock window.performance.getEntriesByType的问题
你当前代码的问题在于,把getEntriesByType赋值成了一个包含windowPerformanceFixture的对象,而不是一个可调用的函数,所以运行测试时会抛出performance.getEntriesByType is not a function的错误。
下面是两种正确的Mock方式:
方式一:用jasmine创建Spy对象(推荐,方便验证调用)
// 先创建performance的spy对象,指定要mock的方法 const mockPerformance = jasmine.createSpyObj('Performance', ['getEntriesByType']); // 设置调用getEntriesByType时返回你的fixture数据 mockPerformance.getEntriesByType.and.returnValue(windowPerformanceFixture); // 构建mock的window对象 const mockWindowService = { performance: mockPerformance }; TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ { provide: WINDOW_TOKEN, useValue: mockWindowService }, ], });
方式二:直接定义函数(适合不需要验证调用的场景)
如果不需要验证getEntriesByType的调用次数、参数等,也可以直接用普通函数返回fixture:
const mockWindowService = {}; Object.defineProperty(mockWindowService, 'performance', { value: { // 直接写成箭头函数返回你的fixture getEntriesByType: () => windowPerformanceFixture }, }); TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ { provide: WINDOW_TOKEN, useValue: mockWindowService }, ], });
如果需要验证这个方法的调用情况(比如是否被调用、传入的参数是否正确),第一种方式更合适,你可以在测试用例中添加如下验证:
expect(mockPerformance.getEntriesByType).toHaveBeenCalledWith('navigation');
内容的提问来源于stack exchange,提问作者UserRomain1234
相关产品推荐
相关产品推荐

