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

React集成测试中如何全局Mock axios-cache-interceptor?

解决React测试中mock axios-cache-interceptor的报错问题

错误原因

你直接导入了axios-cache-interceptor中的真实setupCache函数,它本身不是jest生成的mock函数,自然没有mockReturnValue方法,所以会抛出Cannot read properties of undefined (reading 'mockReturnValue')错误。

解决方法

需要通过jest.mock完整mock整个axios-cache-interceptor模块,让setupCache变成jest mock函数,具体有两种写法:

写法一:在mock工厂函数中直接返回目标对象

修改setupTests.js如下:

import '@testing-library/jest-dom/extend-expect'
import { jest } from '@jest/globals'

// 全局mock整个axios-cache-interceptor模块
jest.mock('axios-cache-interceptor', () => ({
  setupCache: jest.fn(() => ({
    // 缓存相关方法
    get: jest.fn(),
    set: jest.fn(),
    reset: jest.fn(),
    // 必须模拟axios实例的核心方法(组件中用到的都要加)
    get: jest.fn(),
    post: jest.fn(),
    put: jest.fn(),
    delete: jest.fn()
  }))
}))

写法二:先mock模块再设置返回值

如果你需要后续在测试中动态修改返回值,可以用这种方式:

import '@testing-library/jest-dom/extend-expect'
import { jest } from '@jest/globals'
import { setupCache } from 'axios-cache-interceptor'

// 先mock整个模块,此时导入的setupCache已经是mock函数
jest.mock('axios-cache-interceptor')

// 定义模拟的缓存+axios实例对象
const mockXhr = {
  get: jest.fn(),
  set: jest.fn(),
  reset: jest.fn(),
  get: jest.fn(),
  post: jest.fn()
}

// 设置setupCache的返回值
setupCache.mockReturnValue(mockXhr)

注意事项

  • 模拟的对象必须包含组件中用到的axios方法(比如get/post),因为xhr是经过缓存包装后的axios实例,组件会调用这些方法发起请求。
  • 这种全局mock会作用于所有测试用例,如果某个测试需要真实的缓存功能,可以在该测试文件中用jest.unmock('axios-cache-interceptor')取消mock。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 22:15:07