Basic usage:
- create a directory
mock-server
- place some handler files in it (read below for how to write them)
- run
mock-server
root
: mock server root directory, defaults tomock-server
port
: mock server port, defaults to3456
delay
: milliseconds to delay all responses by, defaults to 0watch
: boolean flag, makes the server reload on file changesserveConfig
: boolean flag, serves a config script at/app-config.js
. The script is generated by @staticdeploy/app-config from environment variables and - if a.env
file il present - variables defined in itrequire
: require a module before startup, can be used multiple timesuseHttps
: boolean flag, makesmock-server
serve requests via https. When enabledmock-server
generates a self signed certificate that your borswer needs to trust before being able to make API calls to the server. To trust the certificate, visit https://localhost:3456 and dismiss the security warningmiddleware
: path to a file exporting an array of express middleware. The path should be relative to the mock server root directory. Defaults tomiddleware.js
Handler files are files whose basename matches an http method:
mock-server/get.js
, mock-server/users/post.js
etc.
Handler files export an express route handler:
// mock-server/get.js
module.exports = (req, res) => {
res.status(200).send("OK");
};
The function exported by a handler file is registered as the handler for the
route whose path matches the handler file's path relative to the mock-server
directory, and whose method matches the handler file's name. Examples:
- the function exported by
mock-server/get.js
is registered as the handler for routeGET /
- the function exported by
mock-server/users/post.js
is registered as the handler for routePOST /users
You can also use route params:
- the function exported by
mock-server/users/{userId}/get.js
is registered as the handler for routeGET /users/:userId
Which you can access as you would in express:
// mock-server/users/{userId}/get.js
module.exports = (req, res) => {
console.log(req.params.userId);
res.status(200).send(`userId: ${req.params.userId}`);
};
Note: the path syntax for parametric routes is
.../{param}/...
instead of.../:param/...
because the latter path is not valid for some filesystems (eg NTFS)
Request bodies are parsed according to their mime-type:
- application/json:
req.body
is an object, the parsed json body - text/*:
req.body
is as string, the body - application/x-www-form-urlencoded:
req.body
is an object, the parsed urlencoded body - */*:
req.body
is a buffer, the raw body
mock-server
adds a delay
method to the express response object which you can
use to delay individual responses:
module.exports = (req, res) => {
res
// Delay in milliseconds
.delay(1000)
.status(200)
.send("Delayed response");
};
Read the validation guide to learn how to validate requests received by the mock-server, as well as responses generated by it.