Extended Response Patterns
The second argument of any route method in method in a MockServer
instance is the response pattern. This pattern can be a number (the HTTP status to return) or an object specifying additional data to return with the response. This is helpful when you’re making requests that expect a specific response format.
Extended response pattern keys
The following keys can be used in the response pattern object:
status
(required) - the HTTP status code to return.headers
- HTTP headers to return with the response.body
- the body of the response to return. This can be a string, an object (which is treated as JSON), or anArrayBuffer
.
The response pattern keys are used to create a new Response
object that is returned when the associated request pattern matches the request.
Responding with a specific status code
If you’d like to respond to a request with a specific status code, you can use the status
key in the response pattern object. Here’s an example:
This route will respond to any GET request to /users
with a status code of 200. Of course, if you are only returning a status code, you can pass the status code as the second argument to the route method:
Responding with specific headers
If you’d like to respond to a request with specific headers, you can use the headers
key in the response pattern object. Here’s an example that simulates a redirect:
This route will respond to any GET request to /redirect
with a status code of 301 and a Location
header that redirects the client to https://example.com
.
Responding with a specific body
If you’d like to respond to a request with a specific body, you can use the body
key in the response pattern object. Here’s an example:
This route will respond to any GET request to /users
with a status code of 200 and a JSON response body containing an id
and name
property. There’s no need to call JSON.stringify
on the object; Mentoss will handle that for you.
Responding with a specific body and headers
You can combine the headers
and body
keys in the response pattern object to respond to a request with specific headers and a specific body. Here’s an example:
This route will respond to any GET request to /users
with a status code of 200, a Content-Type
header of application/json
, and a JSON response body containing an id
and name
property.