Mocking
To view this content, buy the book! 😃🙏
Or if you’ve already purchased.
Mocking
If you’re jumping in here,
git checkout 25_0.2.0
(tag 25_0.2.0, or compare 25...mocking)
Mocking API responses—providing the client with fake (mock) data—is easy in GraphQL because we have a schema that tells us the structure of the data and the type of each field. And it’s super easy with Apollo Server—we just add mock: true
:
const server = new ApolloServer({
typeDefs,
resolvers,
mock: true
})
Apollo needs to know how to mock custom types, so we need a mock Date
for our app:
const mocks = {
Date: () => new Date()
}
const server = new ApolloServer({
typeDefs,
resolvers,
dataSources,
context,
formatError,
mocks
})
Now when we make a reviews
query, all the fields we select get returned with mock data:
If we want them to look more like real data, we can use the casual
library for fake data generation:
import casual from 'casual'
const mocks = {
Date: () => new Date(),
Review: () => ({
text: casual.sentence,
stars: () => casual.integer(0, 5)
}),
User: () => ({
firstName: casual.first_name,
lastName: casual.last_name,
username: casual.username,
email: casual.email,
photo: `https://placekitten.com/100/100`
})
}
To make the results array have a variable number of results (the default is two items for all lists), we could add this to make it return between 0 and 3 items:
import { ApolloServer, MockList } from 'apollo-server'
const mocks = {
...
Query: () => ({
reviews: () => new MockList([0, 3])
})
If we created a new app with mocking, and then we wanted to start writing real resolvers, we could add resolvers
and mockEntireSchema: false
:
const server = new ApolloServer({
typeDefs,
mocks,
resolvers,
mockEntireSchema: false
})
Then our resolvers would be used first, and mocks would be used for all the fields for which we hadn’t yet written resolvers.
We can also mock a schema written in a different language than JavaScript or a schema from a third-party GraphQL API. First we download the Apollo CLI, and then we use it to download the target API’s schema:
$ npm i -g apollo
$ apollo schema:download --endpoint https://api.spacex.land/graphql schema.json
Then we start a simple Apollo Server:
const { buildClientSchema } = require('graphql')
const introspectionResult = require('./schema.json')
const { ApolloServer } = require('apollo-server')
const schema = buildClientSchema(introspectionResult.data)
const server = new ApolloServer({
schema,
mocks: true
})
server.listen().then(({ url }) => {
console.log(`Server ready at ${url}`)
})
To test it, we do:
$ git clone https://github.com/GraphQLGuide/mock-external-schema.git
$ cd mock-external-schema
$ npm install
$ npm start
And we open localhost:4000 to issue a query: