【问题标题】:Cypress not seeing graphql request赛普拉斯没有看到 graphql 请求
【发布时间】:2021-11-11 05:47:23
【问题描述】:

这似乎是一个长期存在的问题:

在 cypress 界面中,我的应用程序无法发送任何 graphql 请求或接收任何响应。因为是fetch类型。

这是cypress中的网络状态:

但在普通浏览器中,我实际上有几个 graphql 请求,比如这里:

我知道已经有很多讨论和解决方法,例如使用 polyfill 来解决这个问题,如下所示:

但不幸的是,它们不适用于我的情况。

感谢任何形式的帮助。

p.s.:我使用的是 cypress 8.3.0,React 作为前端,并且使用 apollo 客户端和 apollo 服务器来处理所有 graphql 的东西。


编辑:

同样的拦截:

   cy.intercept('POST', Cypress.env('backendpiUrl') + '/graphql', req => {
      if (req.body.operationName === 'updateItem') {
        req.alias = 'updateItemMutation';
      }
    });

cypress 控制台示例:

可以看到所有的请求都是基于XHR的,没有graphql的fetch请求

【问题讨论】:

    标签: graphql cypress apollo-client e2e-testing apollo-server


    【解决方案1】:

    链接是旧的,unfetch polyfill 不再需要。由于引入了cy.intercept()fetch 可以被等待、被存根等等。

    这是文档Working with GraphQL 和一个有趣的文章Smart GraphQL Stubbing in Cypress(注意route2intercept 的早期名称)

    更多最新消息,两天前发布bahmutov - todo-graphql-example

    此包中的关键辅助函数:

    import {
      ApolloClient,
      InMemoryCache,
      HttpLink,
      ApolloLink,
      concat,
    } from '@apollo/client'
    
    // adding custom header with the GraphQL operation name
    // https://www.apollographql.com/docs/react/networking/advanced-http-networking/
    const operationNameLink = new ApolloLink((operation, forward) => {
      operation.setContext(({ headers }) => ({
        headers: {
          'x-gql-operation-name': operation.operationName,
          ...headers,
        },
      }))
      return forward(operation)
    })
    
    const httpLink = new HttpLink({ uri: 'http://localhost:3000' })
    
    export const client = new ApolloClient({
      link: concat(operationNameLink, httpLink),
      fetchOptions: {
        mode: 'no-cors',
      },
      cache: new InMemoryCache(),
    })
    

    样本测试

    describe('GraphQL client', () => {
      // make individual GraphQL calls using the app's own client
    
      it('gets all todos (id, title)', () => {
        const query = gql`
          query listTodos {
            # operation name
            allTodos {
              # fields to pick
              id
              title
            }
          }
        `
        cy.wrap(
          client.query({
            query,
          }),
        )
          .its('data.allTodos')
          .should('have.length.gte', 2)
          .its('0')
          .should('deep.equal', {
            id: todos[0].id,
            title: todos[0].title,
            __typename: 'Todo',
          })
      })
    

    请显示您的测试和错误(或拦截失败)。

    【讨论】:

    • 感谢 Paolo,我已经更新了主要内容中的 cypress 控制台截图,请查看。但是我仍然困惑的是,你的意思是我必须在看到它之前拦截graphql请求吗?我确实使用代码来拦截它,但在柏树中仍然没有看到
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2020-08-23
    • 1970-01-01
    • 2020-02-08
    • 2020-12-23
    • 1970-01-01
    • 2020-05-09
    相关资源
    最近更新 更多