Skip to Content

mockResolve Hook Configuration

Published: November 23, 2021

Mocks are an essential aspect of the API Lifecycle. There might be situations where you're not able to use a real API or you want to use some special responses during testing.

WunderGraph makes it very easy to configure mocks, but that's not all. We wanted to make mocks extra convenient, so we're generating some code for you to make mocking easy.

Mocks are simply TypeScript functions, executed by a NodeJS runtime. This means, you can include any npm package you want, talk to a database or simply use in memory structures.

You don't have to guess what data to return. Once your Operations are defined, WunderGraph generates models for the mock configuration. This way, all you have to do is implement a function and return some data.

To enable mocks for an Operation, simply implement the mockResolve function in the hooks configuration.

// wundergraph.hooks.ts
const randomInt = (max: number) => Math.floor(Math.random() * Math.floor(max)) + 1
const wunderGraphHooks = configureWunderGraphHooks({
queries: {
// the following Object configures all hooks for the Operation "FakeProducts"
FakeProducts: {
// simply implement the mockResolve function to enable mocks for this Operation
// you have access to the request context, including the current user object
// as well as the input, this way you can build dynamic mocks as well
mockResolve: async (ctx,input) => {
// return the data using autocompletion
// you can put any logic here
return {
data: {
topProducts: [
{
name: "foo",
price: randomInt(100),
upc: "bar",
},
{
name: "foo",
price: randomInt(100),
upc: "bar2"
}
]
}
}
}
},
// this is the configuration for the "OasUsers" Operation
OasUsers: {
// another mock implementation, enabling mocks for OasUsers as well
mockResolve: async () => {
return {
data: {
getUsers: [
{
name: "Jens",
country_code: "DE",
id: 1,
}
]
}
}
}
}
}
});

Product

Comparisons

Subscribe to our newsletter!

Stay informed when great things happen! Get the latest news about APIs, GraphQL and more straight into your mailbox.

© 2021 WunderGraph