Q16 of 20 · GraphQL
How do you mock a GraphQL API for testing?
Short answer
Short answer: Mock at the schema level (a mock server that returns schema-valid responses from the SDL) or at the network level (MSW intercepts the GraphQL request and returns canned data). Schema-based mocking keeps mocks honest to the contract; network-level suits frontend tests.
Detail
Two main approaches, picked by what you're testing:
Schema-based mocking — feed the mock server your schema SDL and it returns type-valid responses automatically (e.g. Apollo Server's mocking, graphql-tools). The win: mocks can't drift from the contract — if the schema says a field is an Int!, the mock returns an int. Good for backend/integration tests and for unblocking frontend work before resolvers exist.
Network-level mocking — intercept the outgoing GraphQL POST and return canned JSON. MSW has first-class GraphQL handlers that match on operation name, so frontend tests run against realistic responses with no server. Good for component/UI tests.
Testing discipline either way:
- Keep the mock's shapes aligned with the real schema (schema-based does this for free; network-level needs review).
- Mock the error and partial-success cases, not just happy paths — that's where GraphQL bugs hide.
- Don't let a green test against a stale mock substitute for at least some tests against the real endpoint.
// WHAT INTERVIEWERS LOOK FOR
// Related questions