Skip to content
Latchkey

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 /graphql with the query in the body.
  • Match the response data object 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 errors array, so assert on data, not just status.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →