Mock Server API Definition
The Mock Server API is modelled on ExpressJS and Sinatra. If you are familiar with either of these frameworks you will know that they provide a clean, simple model for working with HTTP requests and responses.
METHODS
mock.define(path, method, callback)
The mock.define() method configures HTTP routes. The following snippet illustrates the simplest route definition possible. Mock Server translates the path strings to regular expressions, used internally to match incoming requests. Query strings are not considered when performing these matches, for example "GET /" would match the following route, as would "GET /?user=bob".
mock.define("/", "GET", function(req, res) {
res.send("Hello world");
})
The callback is always passed a Request object and a Response object. Route parameters can be specified using {param_name}
in paths. For example, if you have a route /user/{name}
, then the "name" property is available to you as req.params.name.
mock.define("/user/{name}", "get", function(req, res) {
res.send("Hello " + req.params["name"]);
})
Its important to note that all mock.define() blocks must end with a call to send a response such as res.send(). Without this call your service will timeout and not return a successful result. See the Response section for more details.
Request
The req object represents the request message and has properties for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the object is always referred to as req (and the response message is res) but its actual name is determined by the parameters to the callback function in which you’re working.
PROPERTIES
req.params
This property is an array containing property names mapped to named route "parameters", defaults to {}
. For example, if you have a route /user/{name}
then the "name" property is available to you at req.params.name
// GET /user/bob
req.params.name
// = "bob"
req.query
This property is an object containing the parsed query string, defaults to {}
.
// GET /user?name=bob
req.query.name
// = "bob"
// GET /track?id=8efd&parcel[speed]=express
req.query.id
// = 8efd
req.query.parcel.speed
// = express
req.body
This property is an object containing the parsed request body, defaults to {}
. The body will be parsed based on the "Content-Type" header.
// POST {"name": "bob"}
req.body.name
// = "bob"
req.cookies
This property is an object that contains the parsed cookies sent by the user-agent
// Cookie: name=bob
req.cookies.name
// = "bob"
req.url
This property returns the original request URL.
// GET /user?name=bob
req.url
// = "/user?name=bob"
req.path
This property returns the request URL pathname
// example.com/user?name=bob
req.path
// = "/user"
req.accepted
This property is an array of Accepted media types.
[ { value: 'application/json',
quality: 1,
type: 'application',
subtype: 'json'},
{ value: 'text/xml',
quality: 0.5,
type: 'text',
subtype: 'xml' } ]
req.ip
This property returns the originating IP address of the request
req.ip
// = "127.0.0.1"
METHODS
req.get(field)
This function returns the case-insensitive request header for field.
req.get("Content-Type")
// = "application/json"
req.get("content-type")
// = "application/json"
req.is(type)
Check if the incoming request matches the given mime type. If "Content-Type" header field isn't present on the request, it will return false
// with Content-Type: text/html
req.is('html');
req.is('text/html');
req.is('text/*');
// = true
req.is('json')
// = false
Response
The res object represents the response message that Mock Server sends in response to a request message. Use the res object to set response heaers, status codes and more. In this documentation and by convention, the object is always referred to as res (and the request message is req) but its actual name is determined by the parameters to the callback function in which you’re working.
METHODS
res.status(code)
Sets the response status. If you dont set a status, a successful result will default to a 200 status
res.status(404);
res.set(field, [value])
Sets a response header. Sets header field to value where value is a string or an Array of strings. Alternatively, pass in a single argument of type object
res.set('Content-Type', 'application/json');
res.set('X-Header', ['abc', '123']);
res.set({
'Content-Type': 'application/json',
'Content-Length: '123'
})
res.get(field)
Gets the case-insensitive response header for field.
res.get("Content-Type")
// = "application/json"
res.get("content-type")
// = "application/json"
res.type(type)
Sets the Content-Type to the mime lookup of type.
res.type('html')
res.type('json')
res.type('application/json')
res.send([body|status], [body])
Sends a response.
res.send({ name: 'bob' });
res.send('some text');
res.send(404, 'Sorry, cant find that route');
res.send(500, { error: 'Gone pearshaped' });
res.send(200);
If a Content-Type hasnt been set this function will parse the data and set the appropriate header. For example, if you pass in an object then the Content-Type will be set to 'application/json'. When a String is provided the Content-Type is set to 'text/html'. When a Number is provided without a body then a response body string is assigned for you. For example, 200 will respond with the text 'OK'.
Calling this function will also complete execution of your service. Further calls to functions will have no effect.
res.json
Sends a json response. This method is identical to res.send() when an object or array is passed however it will also convert non-objects, such as null, into JSON representation.
res.json(null);
res.json({ name: 'bob' });
res.json(404, { error: 'Not found' });
res.render(template, [locals])
Renders the response using a Liquid template and sends the rendered result. The template parameter must correspond to a template files in the applications /templates directory without the file extension. For example, /templates/users.liquid template is referenced by its name 'users':
res.render('users', { name: 'bob' });
res.render('canned_response');
Locals can be passed in and must be an Object or Array. These are then made available to the template as res.locals. In the above example, 'name' would be available at res.name.