Jest测试调用performance.getEntries()的函数时报错如何解决?
问题原因
jsdom 未完整实现W3C标准的Performance API,仅内置了performance.now()方法,getEntries、getEntriesByName、getEntriesByType等方法均未提供。同时jsdom会锁定全局performance对象的部分属性,直接覆盖global.performance会出现自定义配置不生效的问题。
解决方案
方案1:全局Mock(推荐,无需修改业务代码)
在Jest配置的setupAfterEnv对应的执行文件中添加以下代码,保留原有performance.now()的同时扩展缺失的方法:
// 保留原有performance的现有属性,避免破坏现有功能 const originalPerformance = global.performance; global.performance = { ...originalPerformance, // 可根据业务需要自定义返回值 getEntries: jest.fn(() => []), getEntriesByName: jest.fn(() => []), getEntriesByType: jest.fn(() => []), };
方案2:单用例局部Mock
如果不需要全局生效,仅需要在单个测试文件中Mock,可在测试用例前后添加钩子函数:
beforeEach(() => { jest.spyOn(performance, 'getEntries').mockReturnValue([]); jest.spyOn(performance, 'getEntriesByName').mockReturnValue([]); }); afterEach(() => { // 测试完成后恢复原有实现,避免影响其他用例 jest.restoreAllMocks(); });
如果需要模拟真实的性能条目数据,可自定义Mock的返回值,示例如下:
jest.spyOn(performance, 'getEntriesByName').mockReturnValue([ { name: 'custom-measure', duration: 156, entryType: 'measure', startTime: 1200 } ]);
内容的提问来源于stack exchange,提问作者Kevin Farrugia
相关产品推荐
相关产品推荐

