Mocking resolvers helps you test and develop your GraphQL API without needing a real database or backend.
0
0
Mocking resolvers in GraphQL
Introduction
When you want to try out your GraphQL queries before the real data is ready.
When you need to test your frontend app with sample data quickly.
When you want to check how your API behaves with different data shapes.
When you want to develop parts of your app independently from the backend.
When you want to share a working API example without exposing real data.
Syntax
GraphQL
const mocks = {
Query: {
fieldName: () => mockedValue,
},
TypeName: {
fieldName: () => mockedValue,
},
};Resolvers are functions that return data for each field in your GraphQL schema.
Mocking resolvers means writing simple functions that return fake data instead of real data.
Examples
This mocks the
hello field in the Query type to always return 'Hello, world!'.GraphQL
const mocks = { Query: { hello: () => 'Hello, world!' } };
This mocks the
User type fields name and age with fixed values.GraphQL
const mocks = { User: { name: () => 'Alice', age: () => 30 } };
This mocks a
randomNumber field to return a random number between 0 and 99 each time.GraphQL
const mocks = { Query: { randomNumber: () => Math.floor(Math.random() * 100) } };
Sample Program
This example creates a simple GraphQL server with a greeting field mocked to always return 'Hi there!'.
GraphQL
const { ApolloServer, gql } = require('apollo-server'); const typeDefs = gql` type Query { greeting: String } `; const mocks = { Query: { greeting: () => 'Hi there!' } }; const server = new ApolloServer({ typeDefs, mocks }); server.listen().then(({ url }) => { console.log(`Server ready at ${url}`); });
OutputSuccess
Important Notes
Mocking is great for early development but replace mocks with real resolvers when your backend is ready.
You can use libraries like graphql-tools to help create mocks easily.
Mocks can return static values or dynamic values like random numbers or dates.
Summary
Mocking resolvers lets you simulate API responses without real data.
Use mocks to speed up frontend development and testing.
Mocks are simple functions returning fake data for GraphQL fields.