Last active
September 11, 2019 09:08
-
-
Save jaroslav-kubicek/1e06f18e66ab82d1552cfc7d7171564a to your computer and use it in GitHub Desktop.
Snippet how to mock GraphQL request in cypress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// -------------------------------------- | |
// Mock GraphQL requests with stubs. | |
// Inspiration: https://github.com/cypress-io/cypress-documentation/issues/122 | |
// -------------------------------------- | |
Cypress.Commands.add('visitWithMockedGraphQL', (page, stubs) => { | |
cy.visit(page, { | |
onBeforeLoad: win => { | |
cy.stub(win, 'fetch', handleFetch(stubs)); | |
}, | |
}); | |
}); | |
function handleFetch(stubs) { | |
return (...args) => { | |
const [url, request] = args; | |
const postBody = JSON.parse(request.body); | |
if (url.includes('graphql.kiwi.com')) { | |
const stub = stubs.find( | |
stub => postBody.operationName === stub.operation, // eslint-disable-line no-shadow | |
); | |
if (stub) { | |
return Promise.resolve({ | |
ok: true, | |
json: () => Promise.resolve(stub.response), | |
}); | |
} | |
} | |
// either no GraphQL request or operation that wasn't stubbed | |
return fetch(...args); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment