https://github.com/sandiiarov/cypress-graphql-mock-server-example
yarn global add graphql-mock-server
or
yarn add --dev graphql-mock-server
graphql-mock-server ./schema.graphql -p 4000
gms ./schema.graphql -p 4000
import { serialize } from 'graphql-mock-server';
const mock = {
Query: () => ({
users: () => [
{
id: '1',
name: 'Foo',
},
{
id: '2',
name: 'Baz',
},
],
}),
};
const data = serialize(mock);
// Set mock
fetch('http://localhost:4000/mock', {
method: 'POST',
body: JSON.stringify(data),
});
// Reset mock
fetch('http://localhost:4000/reset', {
method: 'POST',
});
How to write mocks https://www.apollographql.com/docs/graphql-tools/mocking.html
Since the mock functions on fields are actually just GraphQL resolvers, you can use arguments and context in them as well:
{
Query: () => ({
// the number of friends in the list now depends on numPages
paginatedFriends: (root, { numPages }) => new MockList(numPages * PAGE_SIZE),
}),
}
yarn add --dev cypress-graphql-mock-server
// cypress.json
{
"env": {
"GRAPHL_MOCK_SERVER": "http://localhost:<PORT>"
}
}
// support/index.js
import 'cypress-graphql-mock-server';
beforeEach(() => cy.resetGQLMock());
If you are using TypeScript
// tsconfig.json
{
"compilerOptions": {
...
"types": ["cypress-graphql-mock-server"]
}
}
You can also generate TS types using GraphQL schema. You need to use https://github.com/dotansimha/graphql-code-generator with plugins:
- graphql-codegen-typescript-common
- graphql-codegen-typescript-server
- graphql-codegen-typescript-mocks