How to Contract Test a GraphQL API
GraphQL contract testing models the single POST endpoint, pinning the query the consumer sends and the fields it reads back.
Because GraphQL uses one endpoint, the contract captures the request body (query and variables) and the response data shape. Use matchers so only the fields the consumer actually uses are pinned.
Steps
- Define an interaction on
POST /graphqlwith the query in the body. - Match the response
dataobject for only the fields you consume. - Verify on the provider so the resolver still returns those fields.
GraphQL interaction
graphql.consumer.test.js
provider
.uponReceiving('a query for order 42')
.withRequest({
method: 'POST',
path: '/graphql',
headers: { 'Content-Type': 'application/json' },
body: { query: '{ order(id: 42) { id status } }' },
})
.willRespondWith({
status: 200,
body: { data: { order: { id: 42, status: 'shipped' } } },
});Gotchas
- Do not pin the entire schema; match only the fields the consumer selects, or every schema addition breaks the contract.
- GraphQL errors return 200 with an
errorsarray, so assert ondata, not just status.
Related guides
How to Write a Pact Consumer Test and Generate PactsWrite a Pact consumer test that defines expected requests and responses, then run it in CI so Pact generates…
How to Validate OpenAPI Contracts With Optic and oasdiffValidate and lint OpenAPI contracts in CI using Optic to catch breaking changes against captured traffic and…