cypress and graphql code example
Example 1: cypress graphql request
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);
})
Example 2: cypress graphql request example
// --------------------------------------
// 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
})
})
})