A mock server for JS, support HTTP methods and Websocket
npm install @8pattern/jmock
The MockData is defined as following:
{
[Path]: {
[Method1]: [MockItem1],
[Method2]: [MockItem2],
},
[Path2]: { ... }
}
For example:
{
'/mock/item/:productName': {
GET: '@name',
POST: function(cb, req, param) {
if (req.id) {
cb({ id: req.id, name: param.productName })
} else {
cb({ desc: 'error' })
}
}
},
'/mock/item2/.*': {
PUT: {
'name|+1': number
}
},
'/ws/mock': {
WS: (cb, req) => {
if (req.id) {
cb('@name')
}
}
}
}
-
Path <string>
-
It can receive an exact, fuzzy or regular expression pattern to match the request url.
- Exact: the url must match the whole pattern, e.g., "/a/b"
- Fuzzy: support ":<name>" or "*" to match the url.
- :<name>: match only a sub route, i.e. "/:url" can match "/a", but can NOT match "/a/b"
- *: match any routes, i.e., "/route/*" can match "/route/1" and "/route/1/2", but can NOT match "/1/2"
- Reg: use regular expressions as the pattern, i.e., "/(.*?)/(?<id>.>?)"
- Be aware NOT define it as RegExp directly, i.e., use 'a/b/.*' rather than /a/b/.*/. (Because object can't receive RegExp as a key.)
-
The matched string can be found from the third argument of function.
// URL: /a/b // PATTERN: "/:r1/*" or "/(?<r1>.*)/(.*)" (cb, req, param) => { console.log( param[0], // "a" param[1], // "b" param.r1, // "a" ) }
-
priority: Exact > Fuzzy > Reg
-
-
Method<string>
-
All HTTP methods supported by Express.js also SUPPORTED by us.
-
Particularly, WS will be used to present the websocket method.
-
-
MockItem: <string> | <object> | <array> | <function>
- string / object / array
'hello world' | { hello: 'world' } | ['hello', 'world']
Thanks to mockjs, which provides a wonderful data generator, ALL its template strings will also work well in jMock. For example:
'@name' => "Sharon Walker" { "number|1-100": 100 } => { "number": 201 }
-
function
- argument: callback<function>, reqParams<object> routeParams<object>
- return:
function(cb, req, param) { if(req.id === 0) { cb('success') } else if (param.name) { cb('success') } else { setTimeout(() => { cb('fail') }, 200) } }
The callback function also receive a MockItem (except function) as the only argument, so the grammer of mockjs also works. For example:
(cb) => { cb({ name: '@name' }) } // same as { name: '@name' }
- firstly, you should prepare a mock data file, and export it by CommonJS. For example:
module.exports = {
'/mock/name': {
'GET': '@name'
}
}
- then, code the command in the shell.
jmock [--file=./mockdata.js] [--port=3000]
Two arguments should be defined:
- mock file: --file or -f
- e.g., --file=./mockdata.js.
- if not asign it, the mock data will be {} by default
- port: --port or -p
- e.g., --port=3001
- 3000 by default
const JMock = require('@8pattern/jmock')
const port = 3000
const mockData = {
'/mock/name': {
'GET': '@name'
}
}
const jmock = new JMock(data)
jmock.start(port)
ENJOY YOUR MOCK DATA NOW!