1 const query = `{
2 findUser(username:"hello")
3 {
4 id
5 }
6 }`;
7
8 cy.request(
9 {
10 url: 'http://localhost/graphql/', // graphql endpoint
11 body: { query }, // or { query: query } depending if you are writing with es6
12 failOnStatusCode: false // not a must but in case the fail code is not 200 / 400
13 }
14 ).then((res) => {
15 cy.log(res);
16 })
1describe('my page', () => {
2 beforeEach(function() {
3 // Fetch fixtures.
4 cy.fixture('allCars').as('carsQuery')
5 })
6
7 context('mock & visit', () => {
8 beforeEach(function() {
9 cy.mockGraphQL([this.carsQuery])
10
11 cy.visit('http://localhost:8080')
12 })
13
14 it('my action', () => {})
15 })
16})
1// --------------------------------------
2// Mock GraphQL requests with stubs.
3// --------------------------------------
4Cypress.Commands.add('mockGraphQL', stubs => {
5 cy.on('window:before:load', win => {
6 cy.stub(win, 'fetch', (...args) => {
7 console.log('Handling fetch stub', args)
8 const [url, request] = args
9 const postBody = JSON.parse(request.body)
10 let promise
11
12 if (url.indexOf('api') !== -1) {
13 stubs.some(stub => {
14 if (postBody.operationName === stub.operation) {
15 console.log('STUBBING', stub.operation)
16 promise = Promise.resolve({
17 ok: true,
18 text() {
19 return Promise.resolve(JSON.stringify(stub.response))
20 }
21 })
22 return true
23 }
24 return false
25 })
26 }
27
28 if (promise) {
29 return promise
30 }
31
32 console.log('Could not find a stub for the operation.')
33 return false
34 })
35 })
36})