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

如何使用Jest监听全局fetch调用并获取被请求的API地址

实现方案

Jest 生成的 spy 会自动记录所有被监听函数的调用参数,fetch 调用时第一个入参就是请求地址(字符串或 Request 实例),你可以直接通过内置属性获取,也可以按需求封装为你要的调用形式。


方案1:直接使用 Jest 内置属性(无需额外封装)

spy.mock.calls 是一个二维数组,每一项对应一次 fetch 调用的所有入参,第一个元素就是请求地址:

const spy = jest.spyOn(global, 'fetch').mockResolvedValue({
  json: jest.fn().mockResolvedValue(user)
})

// 打印所有发起过的 fetch 请求地址
console.log(spy.mock.calls.map(call => {
  return typeof call[0] === 'string' ? call[0] : call[0].url
}))

// 打印最近一次发起的 fetch 请求地址
const latestCall = spy.mock.calls.at(-1)
if (latestCall) {
  const latestUrl = typeof latestCall[0] === 'string' ? latestCall[0] : latestCall[0].url
  console.log(latestUrl)
}

方案2:封装为 spy.showFetchURL 调用形式

通过给 spy 挂载 getter 即可实现你要求的调用效果,访问属性时自动打印地址:

const spy = jest.spyOn(global, 'fetch').mockResolvedValue({
  json: jest.fn().mockResolvedValue(user)
})

// 给 spy 添加 showFetchURL getter
Object.defineProperty(spy, 'showFetchURL', {
  get() {
    const calls = this.mock.calls
    if (!calls.length) return '暂未检测到 fetch 请求'
    // 可根据需要调整为返回所有地址/最新地址
    const urls = calls.map(call => typeof call[0] === 'string' ? call[0] : call[0].url)
    console.log(urls.length === 1 ? urls[0] : urls)
    return urls
  }
})

// 直接调用即可打印地址
console.log(spy.showFetchURL)

可选扩展:请求触发时自动打印地址

如果不需要手动调用打印,可以直接在 mock 逻辑里嵌入打印逻辑,每次 fetch 调用时自动输出地址:

const spy = jest.spyOn(global, 'fetch').mockImplementation((urlOrRequest, ...args) => {
  const url = typeof urlOrRequest === 'string' ? urlOrRequest : urlOrRequest.url
  console.log('fetch 发起请求:', url)
  return Promise.resolve({
    json: jest.fn().mockResolvedValue(user)
  })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 12:06:02