Skip to content

Instantly share code, notes, and snippets.

@ronderksen
Last active October 2, 2019 14:17
Show Gist options
  • Save ronderksen/9854ee9c44f867a1fbc2b14190d088b0 to your computer and use it in GitHub Desktop.
Save ronderksen/9854ee9c44f867a1fbc2b14190d088b0 to your computer and use it in GitHub Desktop.
const responseStub = result =>
Promise.resolve({
json() {
return Promise.resolve(result);
},
text() {
return Promise.resolve(JSON.stringify(result));
},
ok: result.ok === undefined ? true : result.ok,
});
function isStub(wrappedMethod) {
return wrappedMethod.restore && wrappedMethod.restore.sinon;
}
let originalFetch;
function getFetchStub(win, { withArgs, as, callsFake }) {
let stub = win.fetch;
if (!isStub(win.fetch)) {
originalFetch = win.fetch;
stub = cy.stub(win, 'fetch');
}
stub
.withArgs(...withArgs)
.as(as)
.callsFake(callsFake);
}
Cypress.Commands.add('mockGraphQL', (getOperationMock) => {
const fetchGraphQL = (path, options, ...rest) => {
const { body } = options;
try {
const { operationName, variables } = JSON.parse(body);
const { test = null, mockResult } = getOperationMock(operationName);
if (typeof test === 'function') {
test(variables);
}
if (mockResult) {
return responseStub(mockResult);
}
return originalFetch(path, options, ...rest);
} catch (err) {
console.log(err);
return responseStub(err);
}
};
return cy.on('window:before:load', win => {
getFetchStub(win, {
withArgs: ['/graphql'],
as: 'fetchGraphQL',
callsFake: fetchGraphQL,
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment