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

如何在Cypress中模拟接口返回图片的响应

失效原因

  1. 直接传入binary编码读取的字符串时,cy.intercept默认会将字符串类的body按照UTF-8编码转码传输,会破坏图片原有的二进制结构,导致浏览器无法识别。
  2. 直接返回带data:image/png;base64,前缀的base64字符串属于前端内联图片的专用格式,服务端响应图片不需要此前缀,浏览器会将前缀识别为图片内容的一部分,导致解析失败。
  3. 额外注意:你的本地图片是png格式,响应头写的image/jpg属于不规范写法,虽然不是核心失效原因,但会增加浏览器解析的兼容性风险。

正确实现方案

方案1:读取本地图片文件返回

cy.readFile('src/assets/logo.png', 'base64').then((imgBase64) => {
  // 将base64转为二进制数组,避免Cypress自动转码
  const imgBinary = Uint8Array.from(atob(imgBase64), char => char.charCodeAt(0))
  cy.intercept('/uploads/test.png', {
    headers: { 'Content-Type': 'image/png' },
    body: imgBinary
  })
})

方案2:直接使用base64字符串返回

先去掉base64的前缀部分,再转为二进制数组传入:

// 仅保留base64编码内容,去掉data:image/png;base64,前缀
const pureBase64 = 'iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAARCUlEQVR4Xu1deXQURRr...'
const imgBinary = Uint8Array.from(atob(pureBase64), char => char.charCodeAt(0))
cy.intercept('/uploads/test.png', {
  headers: { 'Content-Type': 'image/png' },
  body: imgBinary
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 08:15:08