Skip to Content

Configure Mocks

Published: September 09, 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.

To enable the code-generator to generate the mock stubs, add templates.typescript.mocks to the code-generator templates in configureWunderGraphApplication.

Once the code generator ran once, you're able to add type-safe mocks by implementing simple lambda functions.

There's a very simple convention here: If you implement a function, the API call to the origin will be replaced with the Mock. If you remove the function again, the API call will go to the origin again.

Note, your mocks can be static but don't have to. You're free to do anything that Node.JS allows you to do. You could go as far as using Prisma and build mocks with a real database, e.g. SQLite.

import {appMock} from "./generated/mocks";
const randomInt = (max: number) => Math.floor(Math.random() * Math.floor(max)) + 1
const mock = appMock({
queries: {
FakeProducts: (input) => {
return {
data: {
topProducts: [
{
name: "foo",
price: randomInt(100),
upc: "bar",
},
{
name: "foo",
price: randomInt(100),
upc: "bar2"
}
]
}
}
},
OasUsers: () => {
return {
data: {
getUsers: [
{
name: "Jens",
country_code: "DE",
id: 1,
}
]
}
}
}
}
});
configureWunderGraphApplication({
...
mock,
});

Once the mock object is defined, pass it to configureWunderGraphApplication. Otherwise, it's just a JS object doing nothing, no magic happening.


Product

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