Express middleware to mock requests with JSON and JS files.
- File based mocks using JSON and JS files.
- Flexible configuration with rcload.
- Supports preflight requests using cors.
- Uses express style path matching with path-to-regexp.
npm i ermock
const express = require("express");
const ermock = require("ermock");
const app = express();
// Add middleware as early as possible.
app.use(ermock());
// Setup routes etc.
It uses rcload and thus supports the following:
ermock
property inpackage.json
.ermockrc
file in JSON format.ermockrc.json
or.ermockrc.js
fileermock.config.js
file exporting a JS object
Furthemore it also accepts a configuration object when setting up in express, eg.:
app.use(mocker({
root: "/api",
dir: "my-mock-reposnses",
delay: 500,
table: { ... }
}));
The complete configuration will consist of default values, file based configuration (cosmiconfig) and object based configuration merged in the mentioned order.
This makes it possible to dynamically overwrite properties, e.g. the root
prefix upon application load.
The configuration object accepts the following properties:
Property | Type | Default value | Description |
---|---|---|---|
root |
string | "" |
Path prefix, e.g. "/api" |
dir |
string | "" |
Folder name where mock files can be found, e.g. "mocks" |
table |
string or object | {} |
Filename or object with url path as key and filename as key, see below. |
delay |
number | 0 |
Add delay to reponses in milliseconds. |
corsOptions |
object | {} |
Options object to use with cors. |
The table
accepts either a filename (relative to application root) or an object with the table configuration.
If you supply a filename it will be loaded automatically, e.g. mocks/table.json
or mock-table.json
.
The object must:
- have
url path
as key, starting with forward slash and excluding theroot
prefix. - have
filename
as value, either a.json
file or.js
file returning a method.
The path matching is done with path-to-regexp using default options.
Example of table configuration:
// mock-table.json
{
"/myservice/users": "users.json",
"/myservice/user/:id": "user.js
}
// users.json
{
"users": [
1,
2
]
}
// user.js
module.exports = function (props) {
const { id } = props;
if (id === 1) {
return {
id,
name: "Arnold S.",
email: "[email protected]",
username: "T800",
permissions: ["ALL"]
};
} else {
return {
id,
name: "Connor, Sarah",
email: "",
username: "donttrustthemachines",
permissions: ["RESTRICTED"]
}
}
}
When a method is returned from the mock file, it is executed with the match object containing named keys and indexed values from the path matched. See the following example:
// table config
{
"/service/subscription/:id([^/\\?]+)(\\?.*)?": "mockfile.js"
}
// req url:
// "/service/subscription/123?userinfo=true"
// mockfile.js
module.exports = function (props) {
// props = { '0': '?userinfo=true', id: '123' }
}
For detailed configuration of the url path, see the path-to-regexp readme.
MIT