Created
November 15, 2019 01:44
-
-
Save andycarrell/784033e3a361d57d664ae5d782daf6ef to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import { graphql } from "graphql"; | |
import { makeMockedSchema } from "../../../src/graphQLMock"; | |
const resolve = result => ({ | |
json: () => Promise.resolve(result), | |
text: () => Promise.resolve(JSON.stringify(result)), | |
ok: true, | |
}); | |
const fetchMockFor = schema => (_, { body }) => { | |
const { query, variables } = JSON.parse(body); | |
return graphql(schema, query, {}, {}, variables).then(resolve); | |
}; | |
let fetchMock = null; | |
Cypress.Commands.add("mockGraphQLApi", { prevSubject: false }, (mocks = {}) => { | |
fetchMock = fetchMockFor(makeMockedSchema({ mocks })); | |
cy.on("window:before:load", win => { | |
const originalFetch = win.fetch; | |
function fetch(url, ...rest) { | |
if ( | |
fetchMock && | |
url === `https://${Cypress.env("API_SERVICE_DOMAIN")}/query` | |
) { | |
return fetchMock(url, ...rest); | |
} else { | |
return originalFetch(url, ...rest); | |
} | |
} | |
cy.stub(win, "fetch") | |
.as("jasperApiMock") | |
.callsFake(fetch); | |
}); | |
}); | |
Cypress.Commands.add( | |
"updateMockGraphQLApi", | |
{ prevSubject: false }, | |
(mocks = {}) => { | |
if (!fetchMock) { | |
throw new Error( | |
"updateMockGraphQLApi: Attempted to update the mock function before it has been defined. Ensure you call 'mockGraphQLApi' first", | |
); | |
} | |
fetchMock = fetchMockFor(makeMockedSchema({ mocks })); | |
}, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment