You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React/Jest单元测试中如何正确Mock Cache Service Worker API?

正确Mock Service Worker Cache API的Jest测试方案

你遇到的问题核心是测试环境中caches对象未正确挂载,或依赖的常量未定义,导致Promise链式调用出错。以下是具体解决步骤和示例:

1. 问题根源分析

浏览器中caches是挂载在window对象上的,Jest的jsdom测试环境中,直接mockwindow.caches比global.caches更贴近真实场景;另外组件中用到的CURRENT_CACHES.backendPlayerInfo常量,测试时必须确保已定义,否则caches.open会传入undefined,引发后续链式调用错误。

2. 全局基础Mock配置

在测试文件的beforeEach中配置前置mock,确保组件渲染前依赖项就绪:

beforeEach(() => {
  // 定义组件依赖的CURRENT_CACHES常量(如果是导入的模块,也可用jest.mock mock)
  window.CURRENT_CACHES = {
    backendPlayerInfo: 'backend-player-info-cache'
  };

  // 创建mock的Cache实例,包含match、put等方法
  const mockCacheInstance = {
    match: jest.fn(),
    put: jest.fn()
  };

  // mock window.caches.open方法,返回mock的Cache实例
  window.caches = {
    open: jest.fn().mockResolvedValue(mockCacheInstance)
  };
});

3. 不同场景测试用例示例

场景1:存在缓存数据时的逻辑验证

test('组件优先使用缓存数据', async () => {
  // 模拟cache.match返回有效缓存响应
  const mockCachedResponse = new Response(JSON.stringify({ playerInfo: 'cached-player-data' }));
  window.caches.open.mockResolvedValue({
    match: jest.fn().mockResolvedValue(mockCachedResponse)
  });

  // 渲染目标组件
  render(<YourTargetComponent />);

  // 添加断言逻辑,比如验证缓存数据是否渲染
  // expect(screen.getByText('cached-player-data')).toBeInTheDocument();
});

场景2:无缓存时触发API调用

test('无缓存时组件调用API获取数据', async () => {
  // 模拟cache.match返回undefined,表示无缓存
  window.caches.open.mockResolvedValue({
    match: jest.fn().mockResolvedValue(undefined)
  });

  // mock fetch API(如果组件用fetch调用接口)
  const mockApiResponse = new Response(JSON.stringify({ playerInfo: 'api-fetched-data' }));
  window.fetch = jest.fn().mockResolvedValue(mockApiResponse);

  // 渲染组件
  render(<YourTargetComponent />);

  // 断言fetch被正确调用
  expect(window.fetch).toHaveBeenCalledWith('mysite.com/api/myapi');
  // 验证API返回数据是否渲染
  // expect(await screen.findByText('api-fetched-data')).toBeInTheDocument();
});

4. 常见问题排查

如果仍出现Cannot read properties of undefined (reading 'then'),检查:

  • CURRENT_CACHES.backendPlayerInfo是否在测试中正确定义,确保caches.open的参数不为undefined。
  • caches.open是否用mockResolvedValue返回Promise(不能用mockReturnValue)。
  • mock是否在组件渲染前执行,避免组件初始化时caches仍为undefined。

内容的提问来源于stack exchange,提问作者soul16

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 04:17:19