Mocking

Mock your GraphQL data based on a schema.

The strongly-typed nature of a GraphQL API lends itself extremely well to mocking. This is an important part of a GraphQL-First development process, because it enables frontend developers to build out UI components and features without having to wait for a backend implementation.

Even when the UI is already built, it can let you test your UI without waiting on slow database requests, or build out a component harness using a tool like React Storybook without needing to start a real GraphQL server.

Default mock example

Let’s take a look at how we can mock a GraphQL schema with just one line of code, using the default mocking logic you get out of the box with graphql-tools.

See a complete runnable example on Launchpad.

To start, let’s grab the schema definition string from the makeExecutableSchema example in the “Generating a schema” article.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import { graphql } from 'graphql';
// Fill this in with the schema string
const schemaString = `...`;
// Make a GraphQL schema with no resolvers
const schema = makeExecutableSchema({ typeDefs: schemaString });
// Add mocks, modifies schema in place
addMockFunctionsToSchema({ schema });
const query = `
query tasksForUser {
user(id: 6) { id, name }
}
`;
graphql(schema, query).then((result) => console.log('Got result', result));

Note: If your schema has custom scalar types, you still need to define the __serialize, __parseValue, and __parseLiteral functions, and pass them inside the second argument to makeExecutableSchema.

This mocking logic simply looks at your schema and makes sure to return a string where your schema has a string, a number for a number, etc. So you can already get the right shape of result. But if you want to use the mocks to do sophisticated testing, you will likely want to customize them to your particular data model.

Customizing mocks

This is where the mocks option comes in, it’s an object that describes your desired mocking logic. This is similar to the resolverMap in makeExecutableSchema, but has a few extra features aimed at mocking.

It allows you to specify functions that are called for specific types in the schema, for example:

1
2
3
4
5
{
Int: () => 6,
Float: () => 22.1,
String: () => 'Hello',
}

You can also use this to describe object types, and the fields can be functions too:

1
2
3
4
5
6
{
Person: () => ({
name: casual.name,
age: () => casual.integer(0, 120),
}),
}

In this example, we are using casual, a fake data generator for JavaScript, so that we can get a different result every time the field is called. You might want to use a collection of fake objects, or a generator that always uses a consistent seed, if you are planning to use the data for testing.

Using MockList in resolvers

You can also use the MockList constructor to automate mocking a list:

1
2
3
4
5
6
7
8
{
Person: () => ({
// a list of length between 2 and 6
friends: () => new MockList([2,6]),
// a list of three lists of two items: [[1, 1], [2, 2], [3, 3]]
listOfLists: () => new MockList(3, () => new MockList(2)),
}),
}

In more complex schemas, MockList is helpful for randomizing the number of entries returned in lists.

For example, this schema:

1
2
3
4
5
6
7
8
9
type Usage {
account: String!
summary: [Summary]!
}
type Summary {
date: String!
cost: Float!
}

By default, the summary field will always return 2 entries. To change this, we can add a mock resolver with MockList as follows:

1
2
3
4
5
{
Person: () =>({
summary: () => new MockList([0, 12]),
}),
}

Now the mock data will contain between zero and 12 summary entries.

Accessing arguments in mock resolvers

Since the mock functions on fields are actually just GraphQL resolvers, you can use arguments and context in them as well:

1
2
3
4
5
6
{
Person: () => ({
// the number of friends in the list now depends on numPages
paginatedFriends: (root, { numPages }) => new MockList(numPages * PAGE_SIZE),
}),
}

You can read some background and flavor on this approach in our blog post, “Mocking your server with one line of code”.

Mocking interfaces

You will need resolvers to mock interfaces. By default addMockFunctionsToSchema will overwrite resolver functions.
By setting the property preserveResolvers on the options object to true, the type resolvers will be preserved.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import {
makeExecutableSchema,
addMockFunctionsToSchema,
addResolveFunctionsToSchema
} from 'graphql-tools'
import mocks from './mocks' // your mock functions
const typeDefs = `
type Query {
fetchMore(listType: String!, amount: Int!, offset: Int!): List
}
type Distributor {
id: Int
name: String
}
type Product {
id: Int
name: String
}
interface List {
amount: Int
offset: Int
total: Int
remaining: Int
}
type DistributorList implements List {
amount: Int
offset: Int
total: Int
remaining: Int
items: [Distributor]
}
type ProductList implements List {
amount: Int
offset: Int
total: Int
remaining: Int
items: [Product]
}
`
const typeResolvers = {
List: {
__resolveType(data) {
return data.typename // typename property must be set by your mock functions
}
}
}
const schema = makeExecutableSchema({
typeDefs
})
addMockFunctionsToSchema({
schema,
mocks,
preserveResolvers: true
})

Mocking a schema using introspection

The GraphQL specification allows clients to introspect the schema with a special set of types and fields that every schema must include. The results of a standard introspection query can be used to generate an instance of GraphQLSchema which can be mocked as explained above.

This helps when you need to mock a schema defined in a language other than JS, for example Go, Ruby, or Python.

To convert an introspection query result to a GraphQLSchema object, you can use the buildClientSchema utility from the graphql package.

1
2
3
4
5
6
import { buildClientSchema } from 'graphql';
import * as introspectionResult from 'schema.json';
const schema = buildClientSchema(introspectionResult);
addMockFunctionsToSchema({schema});

API

addMockFunctionsToSchema

1
2
3
4
5
6
7
import { addMockFunctionsToSchema } from 'graphql-tools';
addMockFunctionsToSchema({
schema,
mocks: {},
preserveResolvers: false,
});

Given an instance of GraphQLSchema and a mock object, addMockFunctionsToSchema modifies the schema in place to return mock data for any valid query that is sent to the server. If mocks is not passed, the defaults will be used for each of the scalar types. If preserveResolvers is set to true, existing resolve functions will not be overwritten to provide mock data. This can be used to mock some parts of the server and not others.

MockList

1
2
3
import { MockList } from 'graphql-tools';
new MockList(length: number | number[], mockFunction: Function);

This is an object you can return from your mock resolvers which calls the mockFunction once for each list item. The first argument can either be an exact length, or an inclusive range of possible lengths for the list, in case you want to see how your UI responds to varying lists of data.

Edit on GitHub