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

Cypress拦截GraphQL请求后Apollo Client useQuery数据为undefined

解决Cypress拦截GraphQL后Apollo useQuery返回undefined的问题

1. 验证hasOperationName函数的正确性

确保该函数能准确识别目标GraphQL请求的operationName。如果请求体是未解析的JSON字符串,需要先解析:

const hasOperationName = (req, operationName) => {
  const body = typeof req.body === 'string' ? JSON.parse(req.body) : req.body
  return body.operationName === operationName
}

2. 强制Apollo使用网络请求而非缓存

在useQuery中设置fetchPolicy: 'network-only',避免Apollo从缓存读取旧数据或空缓存:

const { data, error } = useQuery(UsersQuery, {
  fetchPolicy: 'network-only'
})

3. 确保存根响应格式完全匹配查询结构

检查你的UsersQuery定义,确保存根的data结构和查询字段完全对应。例如如果查询包含额外字段,存根也需要返回对应字段(即使值为null):

req.reply({
  data: {
    users: [{ id: '1', name: null }] // 匹配查询的字段结构
  }
})

4. 显式设置响应的Content-Type

在Cypress的req.reply中明确指定Content-Type为application/json,避免Apollo无法解析响应:

req.reply({
  headers: { 'Content-Type': 'application/json' },
  body: {
    data: { users: [{ id: '1' }] }
  }
})

5. 检查Apollo Client的错误链路配置

如果你的Apollo Client配置了自定义Error Link,确认它没有吞掉错误或阻止数据传递。可以临时注释错误链路,测试是否能正常获取error信息。

6. 验证Apollo缓存是否接收到数据

在Cypress中等待请求后,直接检查Apollo缓存的内容,确认数据是否被正确存入:

cy.wait('@users').then(() => {
  cy.window().then(win => {
    const cachedData = win.__APOLLO_CLIENT__.cache.readQuery({ query: UsersQuery })
    console.log('Cached data:', cachedData) // 打印缓存数据,确认是否存在
  })
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:47:05