mockResolve Hook Configuration
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.tsconst randomInt = (max: number) => Math.floor(Math.random() * Math.floor(max)) + 1const 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 wellmockResolve: async (ctx,input) => {// return the data using autocompletion// you can put any logic herereturn {data: {topProducts: [{name: "foo",price: randomInt(100),upc: "bar",},{name: "foo",price: randomInt(100),upc: "bar2"}]}}}},// this is the configuration for the "OasUsers" OperationOasUsers: {// another mock implementation, enabling mocks for OasUsers as wellmockResolve: async () => {return {data: {getUsers: [{name: "Jens",country_code: "DE",id: 1,}]}}}}}});