@8pattern/jmock 中文文档教程

发布于 5年前 浏览 25 项目主页 更新于 3年前

jMock

一个JS的模拟服务器,支持HTTP方法和Websocket

Install

npm install @8pattern/jmock

Usage

MockData Difination

MockData定义如下:

{
    [Path]: {
        [Method1]: [MockItem1],
        [Method2]: [MockItem2],
    },
    [Path2]: { ... }
}

例如:

{
    '/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 <字符串>

    1. 它可以接收精确的、模糊的或正则表达式模式来匹配请求 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.)
    2. 可以从函数的第三个参数中找到匹配的字符串。

      // URL: /a/b
      // PATTERN: "/:r1/*" or "/(?<r1>.*)/(.*)"
      (cb, req, param) => {
          console.log(
              param[0], // "a"
              param[1], // "b"
              param.r1, // "a"
          )
      } 
      
    3. 优先级:精确 > 模糊 > Reg

  • 方法;

    1. Express.js 支持的所有 HTTP 方法 我们也支持

    2. 特别是,WS 将用于呈现 websocket 方法。

  • MockItem:; | <对象> | <数组> | <功能>

  1. string / object / array

     'hello world' | { hello: 'world' } | ['hello', 'world']
    

    感谢mockjs,它提供了一个很棒的数据生成器,ALL它的模板字符串也可以很好地工作在 jMock 中。 例如:

     '@name' => "Sharon Walker"
     { "number|1-100": 100 } => { "number": 201 }
    
  2. 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)
            }
        }
    

    回调函数也接收一个 MockItem (except function) 作为唯一的参数,所以 mockjs 也有效。 例如:

      (cb) => {
         cb({ name: '@name' })
      }
      // same as { name: '@name' }
    

Run as CMD

  1. firstly, you should prepare a mock data file, and export it by CommonJS. For example:
module.exports = {
    '/mock/name': {
        'GET': '@name'
    }
}
  1. then, code the command in the shell.
jmock [--file=./mockdata.js] [--port=3000]

应定义两个参数:

  • mock file: --file or -f
  1. e.g., --file=./mockdata.js.
  2. if not asign it, the mock data will be {} by default
  • port: --port or -p
  1. e.g., --port=3001
  2. 3000 by default

Run as Script

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!

jMock

A mock server for JS, support HTTP methods and Websocket

Install

npm install @8pattern/jmock

Usage

MockData Difination

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>

    1. 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.)
    2. 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"
          )
      } 
      
    3. priority: Exact > Fuzzy > Reg

  • Method<string>

    1. All HTTP methods supported by Express.js also SUPPORTED by us.

    2. Particularly, WS will be used to present the websocket method.

  • MockItem: <string> | <object> | <array> | <function>

  1. 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 }
    
  2. 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' }
    

Run as CMD

  1. firstly, you should prepare a mock data file, and export it by CommonJS. For example:
module.exports = {
    '/mock/name': {
        'GET': '@name'
    }
}
  1. then, code the command in the shell.
jmock [--file=./mockdata.js] [--port=3000]

Two arguments should be defined:

  • mock file: --file or -f
  1. e.g., --file=./mockdata.js.
  2. if not asign it, the mock data will be {} by default
  • port: --port or -p
  1. e.g., --port=3001
  2. 3000 by default

Run as Script

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!

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文