Apollys
0
Q:

cypress graphql request example

    const query = `{
        findUser(username:"hello")
        {
            id
        }
    }`;

    cy.request(
        {
            url: 'http://localhost/graphql/',  // graphql endpoint
            body: { query },  // or { query: query } depending if you are writing with es6
            failOnStatusCode: false  // not a must but in case the fail code is not 200 / 400
        }
    ).then((res) => {
        cy.log(res);
    })
0
describe('my page', () => {
  beforeEach(function() {
    // Fetch fixtures.
    cy.fixture('allCars').as('carsQuery')
  })

  context('mock & visit', () => {
    beforeEach(function() {
      cy.mockGraphQL([this.carsQuery])

      cy.visit('http://localhost:8080')
    })

    it('my action', () => {})
  })
})
0
// --------------------------------------
// Mock GraphQL requests with stubs.
// --------------------------------------
Cypress.Commands.add('mockGraphQL', stubs => {
  cy.on('window:before:load', win => {
    cy.stub(win, 'fetch', (...args) => {
      console.log('Handling fetch stub', args)
      const [url, request] = args
      const postBody = JSON.parse(request.body)
      let promise

      if (url.indexOf('api') !== -1) {
        stubs.some(stub => {
          if (postBody.operationName === stub.operation) {
            console.log('STUBBING', stub.operation)
            promise = Promise.resolve({
              ok: true,
              text() {
                return Promise.resolve(JSON.stringify(stub.response))
              }
            })
            return true
          }
          return false
        })
      }

      if (promise) {
        return promise
      }

      console.log('Could not find a stub for the operation.')
      return false
    })
  })
})
-1

New to Communities?

Join the community