Skip to content

Instantly share code, notes, and snippets.

@jaroslav-kubicek
Last active September 11, 2019 09:08
Show Gist options
  • Save jaroslav-kubicek/1e06f18e66ab82d1552cfc7d7171564a to your computer and use it in GitHub Desktop.
Save jaroslav-kubicek/1e06f18e66ab82d1552cfc7d7171564a to your computer and use it in GitHub Desktop.
Snippet how to mock GraphQL request in cypress
// --------------------------------------
// 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