Skip to content

Mocking a GraphQL API

Right-click a folder ▸ Add ▸ GraphQL server.

FieldRole
SchemaThe type definitions, in SDL
Mock resolversA JSON object whose keys are of the form Type.field, for example Query.pets
Resolver scriptJavaScript receiving (parent, args, context)

The script wins over the canned values when it is filled in: that is what lets you vary the response according to the arguments received.

A GraphQL server item: the listening address, the SDL schema served, and the map of predefined resolvers, key Type.field → value

The quickest route: the schema describes the shape, the resolvers give the content.

type Animal { id: ID!, nom: String!, espece: String! }
type Query { animaux: [Animal!]! }
{
"Query.animaux": [
{ "id": "1", "nom": "Mistigri", "espece": "chat" },
{ "id": "2", "nom": "Rex", "espece": "chien" }
]
}

For when the response has to depend on the input:

// (parent, args, context)
if (args.espece) {
return animaux.filter((a) => a.espece === args.espece);
}
return animaux;

The subscriptions declared in the schema are served too: a client can connect to them and receive the messages emitted.

The GraphQL server and GraphQL server close actions host the service for the duration of the scenario. See Hosted servers.

Developing a front end before the back end exists, reproducing an error response that is hard to provoke in staging, or freezing a data set for a deterministic test — without depending on a remote service.