Cypress not seeing graphql request

Viewed 738

This seems to be a long lasting issue:

In cypress interface, my application cannot send any graphql request or receive any response. Because it is fetch type.

here is the network status in cypress:

enter image description here

But in normal browser, I actually have several graphql requests, like here:

enter image description here

I know there are already quite several discussions and workarounds, such as using an polyfill to solve this problem such as below:

but unfortunately, they are not working in my case.

Appreciate to the help of any kinds.

p.s.: I am using cypress 8.3.0, React as the front-end, and using apollo client and apollo server for all graphql stuff.


EDIT:

samele intercept:

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

sample cypress console:

enter image description here

You can see that all the requests are XHR based, no graphql's fetch request

1 Answers

The links are old, unfetch polyfill is no longer necessary. Since the introduction of cy.intercept(), fetch is able to be waited on, stubbed etc.

Here's the docs Working with GraphQL and an interesting atricle Smart GraphQL Stubbing in Cypress (Note route2 is an early name for intercept)

More up-to-date, posted two days ago bahmutov - todo-graphql-example

Key helper function from this package:

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(),
})

Sample test

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',
      })
  })

Please show your test and the error (or failing intercept).

Related