-
Notifications
You must be signed in to change notification settings - Fork 91
How to create a mock response
If you need a server-side resource or service which doesn't yet exist or is out of reach, the goal of mocks is to enable you to quickly create one.
If you have lws-mock-response
present in your stack (included by default) you will have the option to set --mocks
.
$ ws --mocks my-mocks-module.js
Here is the minimum code required for a mock module, you can use this as a boilerplate template. Replace MyMockModule
with a more useful name.
module.exports = MockBase => class MyMockModule extends MockBase {
mocks () {
}
}
The mocks
method must return an object with two properties - route
and responses
. The route value can use any Express-style routing syntax, described here in the "Route paths" and "Route parameters" sections.
module.exports = MockBase => class MyMockModule extends MockBase {
mocks () {
return {
route: '/pizzas/:id',
responses: []
}
}
}
The responses
property must contain one or more objects, each with a response
property. The response
property value will be written directly to the Koa ctx
object, meaning on this object you can set any of the standard ctx
response values. The properties you will set must commonly are body
, status
and type
.
This example will respond with 200
(the default statusCode) and the body Margerita
to any request for /pizzas/:id
, e.g. /pizzas/1
.
module.exports = MockBase => class MyMockModule extends MockBase {
mocks () {
return {
route: '/pizzas/:id',
responses: [
{
response: {
body: 'Margerita'
}
}
]
}
}
}