mockjs入门级教程(模拟数据或随机数据生成)

文章目录
  1. 1. 前后端分离
  2. 2. 增加单元测试的真实性
  3. 3. 开发无侵入
  4. 4. 用法简单
  5. 5. 数据类型丰富
  6. 6. 方便扩展
  • 开始 & 安装
    1. 1. Node (CommonJS)
    2. 2. Bower
    3. 3. RequireJS (AMD)
    4. 4. Sea.js (CMD)
    5. 5. Random CLI
  • 语法规范
    1. 数据模板定义规范 DTD
      1. 1. 数据模板中的每个属性由 3 部分构成:属性名、生成规则、属性值:
      2. 2. 注意:
      3. 3. 生成规则和示例:
        1. 3.1. 1. 属性值是字符串 String
        2. 3.2. 2. 属性值是数字 Number
        3. 3.3. 3. 属性值是布尔型 Boolean
        4. 3.4. 4. 属性值是对象 Object
        5. 3.5. 5. 属性值是数组 Array
        6. 3.6. 6. 属性值是函数 Function
        7. 3.7. 7. 属性值是正则表达式 RegExp
    2. 数据占位符定义规范 DPD
      1. 1. 注意:
  • Mock.mock()
    1. Mock.mock( rurl?, rtype?, template|function( options ) )
      1. 1. Mock.mock( template )
      2. 2. Mock.mock( rurl, template )
      3. 3. Mock.mock( rurl, function( options ) )
      4. 4. Mock.mock( rurl, rtype, template )
      5. 5. Mock.mock( rurl, rtype, function( options ) )
      6. 6. rurl
      7. 7. rtype
      8. 8. template
      9. 9. function(options)
      10. 10. options
  • Date
    1. Random.date( format? )
      1. 1. format(可选)
    2. Random.time( format? )
      1. 1. format
    3. Random.datetime( format? )
      1. 1. format
    4. Random.now( unit?, format? )
      1. 1. unit
      2. 2. format
  • Image
    1. Random.image( size?, background?, foreground?, format?, text? )
      1. 1. size
      2. 2. background
      3. 3. foreground
      4. 4. format
      5. 5. text
    2. Random.dataImage( size?, text? )
      1. 1. size
      2. 2. text
  • Color
    1. Random.color()
    2. Random.hex()
    3. Random.rgb()
    4. Random.rgba()
    5. Random.hsl()
  • Text
    1. Random.paragraph( min?, max? )
      1. 1. len
      2. 2. min
      3. 3. max
    2. Random.cparagraph( min?, max? )
    3. Random.sentence( min?, max? )
      1. 1. len
      2. 2. min
      3. 3. max
    4. Random.csentence( min?, max? )
    5. Random.word( min?, max? )
      1. 1. len
      2. 2. min
      3. 3. max
    6. Random.cword( pool?, min?, max? )
      1. 1. pool
      2. 2. min
      3. 3. max
    7. Random.title( min?, max? )
      1. 1. len
      2. 2. min
      3. 3. max
      4. 4. Random.ctitle( min?, max? )
      5. 5. len
      6. 6. min
      7. 7. max
  • Name
    1. Random.first()
    2. Random.last()
    3. Random.name( middle? )
      1. 1. middle
    4. Random.cfirst()
    5. Random.clast()
    6. Random.cname()
  • Web
    1. Random.url( protocol?, host? )
      1. 1. protocol
      2. 2. host
    2. Random.protocol()
    3. Random.domain()
    4. Random.tld()
    5. Random.email( domain? )
      1. 1. domain
    6. Random.ip()
  • Address
    1. Random.region()
    2. Random.province()
    3. Random.city( prefix? )
      1. 1. prefix
    4. Random.county( prefix? )
      1. 1. prefix
    5. Random.zip()
  • Helper
    1. Random.capitalize( word )
    2. Random.upper( str )
    3. Random.lower( str )
    4. Random.pick( arr )
    5. Random.shuffle( arr )
  • Miscellaneous
    1. Random.guid()
    2. Random.id()
    3. Random.increment( step? )
      1. 1. step
  • Mock.valid()
    1. Mock.valid( template, data )
      1. 1. template
      2. 2. data
  • Mock.toJSONSchema()
    1. Mock.toJSONSchema( template )
      1. 1. template
  • Mock.js生成随机数据,拦截 Ajax 请求(随机数据即制造假数据提供给使用)

    前后端分离

    让前端攻城师独立于后端进行开发。

    增加单元测试的真实性

    通过随机数据,模拟各种场景。

    开发无侵入

    不需要修改既有代码,就可以拦截 Ajax 请求,返回模拟的响应数据。

    用法简单

    符合直觉的接口。

    数据类型丰富

    支持生成随机的文本、数字、布尔值、日期、邮箱、链接、图片、颜色等。

    方便扩展

    支持支持扩展更多数据类型,支持自定义函数和正则。

    开始 & 安装

    Node (CommonJS)

    1
    2
    #安装
    npm install mockjs
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    // 使用 Mock
    var Mock = require('mockjs')
    var data = Mock.mock({
    // 属性 list 的值是一个数组,其中含有 1 到 10 个元素
    'list|1-10': [{
    // 属性 id 是一个自增数,起始值为 1,每次增 1
    'id|+1': 1
    }]
    })
    // 输出结果
    console.log(JSON.stringify(data, null, 4))

    Bower

    1
    2
    3
    # 安装
    npm install -g bower
    bower install --save mockjs
    1
    <script type="text/javascript" src="./bower_components/mockjs/dist/mock.js"></script>

    RequireJS (AMD)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    // 配置 Mock 路径
    require.config({
    paths: {
    mock: 'http://mockjs.com/dist/mock'
    }
    })
    // 加载 Mock
    require(['mock'], function(Mock){
    // 使用 Mock
    var data = Mock.mock({
    'list|1-10': [{
    'id|+1': 1
    }]
    })
    // 输出结果
    document.body.innerHTML +=
    '<pre>' +
    JSON.stringify(data, null, 4) +
    '</pre>'
    })
    // ==>{"list": [{"id": 1},{"id": 2},{"id": 3}]}

    Sea.js (CMD)

    因为 Sea.js 社区尚未提供 webpack 插件,所以 Mock.js 暂不完整支持通过 Sea.js 加载。

    一种变通的方式是,依然通过 Sea.js 配置和加载 Mock.js,然后访问全局变量 Mock。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    // 配置 Mock 路径
    seajs.config({
    alias: {
    mock: 'http://mockjs.com/dist/mock.js'
    }
    })
    // 加载 Mock
    seajs.use('mock', function(__PLACEHOLDER) {
    // 使用 Mock(全局变量)
    var data = Mock.mock({
    'list|1-10': [{
    'id|+1': 1
    }]
    });
    document.body.innerHTML +=
    '<pre>' +
    JSON.stringify(data, null, 4) +
    '</pre>'
    })

    Random CLI

    1
    2
    3
    4
    5
    6
    7
    8
    9
    # 全局安装
    $ npm install mockjs -g
    # 执行
    $ random url
    # => http://rmcpx.org/funzwc
    # 帮助
    random -h

    语法规范

    Mock.js 的语法规范包括两部分:

    . 数据模板定义规范(Data Template Definition,DTD)

    . 数据占位符定义规范(Data Placeholder Definition,DPD)

    数据模板定义规范 DTD

    数据模板中的每个属性由 3 部分构成:属性名、生成规则、属性值:

    1
    2
    3
    4
    // 属性名 name
    // 生成规则 rule
    // 属性值 value
    'name|rule': value

    注意:

    . 属性名 和 生成规则 之间用竖线 | 分隔。
    . 生成规则 是可选的。
    . 生成规则 有 7 种格式:
    . ‘name|min-max’: value
    . ‘name|count’: value
    . ‘name|min-max.dmin-dmax’: value
    . ‘name|min-max.dcount’: value
    . ‘name|count.dmin-dmax’: value
    . ‘name|count.dcount’: value
    . ‘name|+step’: value
    . 生成规则 的 含义 需要依赖 属性值的类型 才能确定。
    . 属性值 中可以含有 @占位符。
    . 属性值 还指定了最终值的初始值和类型。

    生成规则和示例:

    1. 属性值是字符串 String
    1
    2
    3
    4
    5
    6
    7
    'name|min-max': string
    通过重复 string 生成一个字符串,重复次数大于等于 min,小于等于 max。
    'name|count': string
    通过重复 string 生成一个字符串,重复次数等于 count。
    2. 属性值是数字 Number
    1
    2
    3
    4
    5
    6
    'name|+1': number
    属性值自动加 1,初始值为 number。
    'name|min-max': number
    生成一个大于等于 min、小于等于 max 的整数,属性值 number 只是用来确定类型。
    'name|min-max.dmin-dmax': number
    生成一个浮点数,整数部分大于等于 min、小于等于 max,小数部分保留 dmin 到 dmax 位。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    Mock.mock({
    'number1|1-100.1-10': 1,
    'number2|123.1-10': 1,
    'number3|123.3': 1,
    'number4|123.10': 1.123
    })
    // =>
    {
    "number1": 12.92,
    "number2": 123.51,
    "number3": 123.777,
    "number4": 123.1231091814
    }
    3. 属性值是布尔型 Boolean

    ‘name|1’: boolean

    随机生成一个布尔值,值为 true 的概率是 1/2,值为 false 的概率同样是 1/2。

    ‘name|min-max’: value

    随机生成一个布尔值,值为 value 的概率是 min / (min + max),值为 !value 的概率是 max / (min + max)。

    4. 属性值是对象 Object

    ‘name|count’: object

    从属性值 object 中随机选取 count 个属性。

    ‘name|min-max’: object

    从属性值 object 中随机选取 min 到 max 个属性。

    5. 属性值是数组 Array

    ‘name|1’: array

    从属性值 array 中随机选取 1 个元素,作为最终值。

    ‘name|+1’: array

    从属性值 array 中顺序选取 1 个元素,作为最终值。

    ‘name|min-max’: array

    通过重复属性值 array 生成一个新数组,重复次数大于等于 min,小于等于 max。

    ‘name|count’: array

    通过重复属性值 array 生成一个新数组,重复次数为 count。

    6. 属性值是函数 Function

    ‘name’: function

    执行函数 function,取其返回值作为最终的属性值,函数的上下文为属性 ‘name’ 所在的对象。

    7. 属性值是正则表达式 RegExp

    ‘name’: regexp

    根据正则表达式 regexp 反向生成可以匹配它的字符串。用于生成自定义格式的字符串。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    Mock.mock({
    'regexp1': /[a-z][A-Z][0-9]/,
    'regexp2': /\w\W\s\S\d\D/,
    'regexp3': /\d{5,10}/
    })
    // =>
    {
    "regexp1": "pJ7",
    "regexp2": "F)\fp1G",
    "regexp3": "561659409"
    }

    数据占位符定义规范 DPD

    占位符 只是在属性值字符串中占个位置,并不出现在最终的属性值中。

    占位符 的格式为:

    1
    2
    @占位符
    @占位符(参数 [, 参数])

    注意:

    1. 用 @ 来标识其后的字符串是 占位符。
    2. 占位符 引用的是 Mock.Random 中的方法。
    3. 通过 Mock.Random.extend() 来扩展自定义占位符。
    4. 占位符 也可以引用 数据模板 中的属性。
    5. 占位符 会优先引用 数据模板 中的属性。
    6. 占位符 支持 相对路径 和 绝对路径。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    Mock.mock({
    name: {
    first: '@FIRST',
    middle: '@FIRST',
    last: '@LAST',
    full: '@first @middle @last'
    }
    })
    // =>
    {
    "name": {
    "first": "Charles",
    "middle": "Brenda",
    "last": "Lopez",
    "full": "Charles Brenda Lopez"
    }
    }

    Mock.mock()

    Mock.mock( rurl?, rtype?, template|function( options ) )

    根据数据模板生成模拟数据。

    Mock.mock( template )

    根据数据模板生成模拟数据。

    Mock.mock( rurl, template )

    记录数据模板。当拦截到匹配 rurl 的 Ajax 请求时,将根据数据模板 template 生成模拟数据,并作为响应数据返回。

    Mock.mock( rurl, function( options ) )

    记录用于生成响应数据的函数。当拦截到匹配 rurl 的 Ajax 请求时,函数function(options) 将被执行,并把执行结果作为响应数据返回。

    Mock.mock( rurl, rtype, template )

    记录数据模板。当拦截到匹配 rurl 和 rtype 的 Ajax 请求时,将根据数据模板 template 生成模拟数据,并作为响应数据返回。

    Mock.mock( rurl, rtype, function( options ) )

    记录用于生成响应数据的函数。当拦截到匹配 rurl 和 rtype 的 Ajax 请求时,函数 function(options) 将被执行,并把执行结果作为响应数据返回。

    rurl

    可选。

    表示需要拦截的 URL,可以是 URL 字符串或 URL 正则。例如 /\/domain\/list\.json/'/domian/list.json'

    rtype

    可选。

    表示需要拦截的 Ajax 请求类型。例如 GET、POST、PUT、DELETE 等。

    template

    可选。

    表示数据模板,可以是对象或字符串。例如{ 'data|1-10':[{}] }'@EMAIL'

    function(options)

    可选。

    表示用于生成响应数据的函数。

    options

    指向本次请求的 Ajax 选项集,含有 url、type 和 body 三个属性,参见 XMLHttpRequest 规范。

    从 1.0 开始,Mock.js 通过覆盖和模拟原生 XMLHttpRequest 的行为来拦截 Ajax 请求,不再依赖于第三方 Ajax 工具库(例如 jQuery、Zepto 等)。
    

    Date

    Random.date( format? )

    . Random.date()
    . Random.date(format)
    返回一个随机的日期字符串。

    format(可选)

    指示生成的日期字符串的格式。默认值为 yyyy-MM-dd。

    可选的占位符参考自 Ext.Date,如下所示:

    Format Description Example
    yyyy A full numeric representation of a year, 4 digits 1999 or 2003
    yy A two digit representation of a year 99 or 03
    y A two digit representation of a year 99 or 03
    MM Numeric representation of a month, with leading zeros 01 to 12
    M Numeric representation of a month, without leading zeros 1 to 12
    dd Day of the month, 2 digits with leading zeros 01 to 31
    d Day of the month without leading zeros 1 to 31
    HH 24-hour format of an hour with leading zeros 00 to 23
    H 24-hour format of an hour without leading zeros 0 to 23
    hh 12-hour format of an hour without leading zeros 1 to 12
    h 12-hour format of an hour with leading zeros 01 to 12
    mm Minutes, with leading zeros 00 to 59
    m Minutes, without leading zeros 0 to 59
    ss Seconds, with leading zeros 00 to 59
    s Seconds, without leading zeros 0 to 59
    SS Milliseconds, with leading zeros 000 to 999
    S Milliseconds, without leading zeros 0 to 999
    A Uppercase Ante meridiem and Post meridiem AM or PM
    a Lowercase Ante meridiem and Post meridiem am or pm
    T Milliseconds, since 1970-1-1 00:00:00 UTC 759883437303
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    Random.date()
    // => "2002-10-23"
    Random.date('yyyy-MM-dd')
    // => "1983-01-29"
    Random.date('yy-MM-dd')
    // => "79-02-14"
    Random.date('y-MM-dd')
    // => "81-05-17"
    Random.date('y-M-d')
    // => "84-6-5"

    Random.time( format? )

    . Random.time()
    . Random.time( format )

    返回一个随机的时间字符串。

    format

    指示生成的时间字符串的格式。默认值为 HH:mm:ss。

    可选的占位符参考自 Ext.Date,请参见 Random.date( format? )。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    Random.time()
    // => "00:14:47"
    Random.time('A HH:mm:ss')
    // => "PM 20:47:37"
    Random.time('a HH:mm:ss')
    // => "pm 17:40:00"
    Random.time('HH:mm:ss')
    // => "03:57:53"
    Random.time('H:m:s')
    // => "3:5:13"

    Random.datetime( format? )

    . Random.datetime()
    . Random.datetime( format )

    返回一个随机的日期和时间字符串。

    format

    指示生成的日期和时间字符串的格式。默认值为 yyyy-MM-dd HH:mm:ss

    可选的占位符参考自 Ext.Date,请参见 Random.date( format? )。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    Random.datetime()
    // => "1977-11-17 03:50:15"
    Random.datetime('yyyy-MM-dd A HH:mm:ss')
    // => "1976-04-24 AM 03:48:25"
    Random.datetime('yy-MM-dd a HH:mm:ss')
    // => "73-01-18 pm 22:12:32"
    Random.datetime('y-MM-dd HH:mm:ss')
    // => "79-06-24 04:45:16"
    Random.datetime('y-M-d H:m:s')
    // => "02-4-23 2:49:40"

    Random.now( unit?, format? )

    . Ranndom.now( unit, format )
    . Ranndom.now()
    . Ranndom.now( format )
    . Ranndom.now( unit )

    返回当前的日期和时间字符串。

    unit

    表示时间单位,用于对当前日期和时间进行格式化。可选值有:year、monthweekdayhourminutesecondweek`,默认不会格式化。

    format

    指示生成的日期和时间字符串的格式。默认值为 yyyy-MM-dd HH:mm:ss

    Random.now() 的实现参考了 Moment.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    Random.now()
    // => "2014-04-29 20:08:38 "
    Random.now('day', 'yyyy-MM-dd HH:mm:ss SS')
    // => "2014-04-29 00:00:00 000"
    Random.now('day')
    // => "2014-04-29 00:00:00 "
    Random.now('yyyy-MM-dd HH:mm:ss SS')
    // => "2014-04-29 20:08:38 157"
    Random.now('year')
    // => "2014-01-01 00:00:00"
    Random.now('month')
    // => "2014-04-01 00:00:00"
    Random.now('week')
    // => "2014-04-27 00:00:00"
    Random.now('day')
    // => "2014-04-29 00:00:00"
    Random.now('hour')
    // => "2014-04-29 20:00:00"
    Random.now('minute')
    // => "2014-04-29 20:08:00"
    Random.now('second')
    // => "2014-04-29 20:08:38"

    Image

    Random.image( size?, background?, foreground?, format?, text? )

    . Random.image()
    . Random.image( size )
    . Random.image( size, background )
    . Random.image( size, background, text )
    . Random.image( size, background, foreground, text )
    . Random.image( size, background, foreground, format, text )

    生成一个随机的图片地址。

    Random.image()用于生成高度自定义的图片地址,一般情况下,应该使用更简单的 Random.dataImage()

    size

    指示图片的宽高,格式为 ‘宽x高’。默认从下面的数组中随机读取一个:

    1
    2
    3
    4
    5
    6
    7
    [
    '300x250', '250x250', '240x400', '336x280',
    '180x150', '720x300', '468x60', '234x60',
    '88x31', '120x90', '120x60', '120x240',
    '125x125', '728x90', '160x600', '120x600',
    '300x600'
    ]

    background

    指示图片的背景色。默认值为 ‘#000000’。

    foreground

    指示图片的前景色(文字)。默认值为 ‘#FFFFFF’。

    format

    指示图片的格式。默认值为 ‘png’,可选值包括:’png’、’gif’、’jpg’。

    text

    指示图片上的文字。默认值为参数 size。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    Random.image()
    // => "http://dummyimage.com/125x125"
    Random.image('200x100')
    // => "http://dummyimage.com/200x100"
    Random.image('200x100', '#fb0a2a')
    // => "http://dummyimage.com/200x100/fb0a2a"
    Random.image('200x100', '#02adea', 'Hello')
    // => "http://dummyimage.com/200x100/02adea&text=Hello"
    Random.image('200x100', '#00405d', '#FFF', 'Mock.js')
    // => "http://dummyimage.com/200x100/00405d/FFF&text=Mock.js"
    Random.image('200x100', '#ffcc33', '#FFF', 'png', '!')
    // => "http://dummyimage.com/200x100/ffcc33/FFF.png&text=!"

    Random.dataImage( size?, text? )

    . Random.dataImage()
    . Random.dataImage( size )
    . Random.dataImage( size, text )

    生成一段随机的 Base64 图片编码。
    如果需要生成高度自定义的图片,请使用Random.image()

    size

    指示图片的宽高,格式为 ‘宽x高’。默认从下面的数组中随机读取一个:

    1
    2
    3
    4
    5
    6
    7
    [
    '300x250', '250x250', '240x400', '336x280',
    '180x150', '720x300', '468x60', '234x60',
    '88x31', '120x90', '120x60', '120x240',
    '125x125', '728x90', '160x600', '120x600',
    '300x600'
    ]

    text

    指示图片上的文字。默认值为参数 size。

    图片的背景色是随机的,取值范围参考自 http://brandcolors.net/。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    Random.dataImage()
    // => "data:image/png;base64,iVBORw0···"
    Random.dataImage('200x100')
    // => "data:image/png;base64,iVBORw0···"
    Random.dataImage('200x100', 'Hello Mock.js!')
    // => "data:image/png;base64,iVBORw0···"

    Color

    Random.color()

    . Random.color()
    随机生成一个有吸引力的颜色,格式为 '#RRGGBB'

    1
    2
    Random.color()
    // => "#3538B2"

    Random.hex()

    Random.hex()
    随机生成一个有吸引力的颜色,格式为 '#RRGGBB'

    1
    2
    Random.hex()
    // => "#3538B2"

    Random.rgb()

    . Random.rgb()
    随机生成一个有吸引力的颜色,格式为 'rgb(r, g, b)'

    1
    2
    Random.rgb()
    // => "rgb(242, 198, 121)"

    Random.rgba()

    . Random.rgba()
    随机生成一个有吸引力的颜色,格式为 'rgba(r, g, b, a)'

    1
    2
    Random.rgba()
    // => "rgba(242, 198, 121, 0.13)"

    Random.hsl()

    . Random.hsl()
    随机生成一个有吸引力的颜色,格式为 'hsl(h, s, l)'

    1
    2
    Random.hsl()
    // => "hsl(345, 82, 71)"

    Text

    Random.paragraph( min?, max? )

    . Random.paragraph()
    . Random.paragraph( len )
    . Random.paragraph( min, max )
    随机生成一段文本。

    len

    指示文本中句子的个数。默认值为 3 到 7 之间的随机数。

    min

    指示文本中句子的最小个数。默认值为 3。

    max

    指示文本中句子的最大个数。默认值为 7。

    1
    2
    3
    4
    5
    6
    7
    8
    Random.paragraph()
    // => "Yohbjjz psxwibxd jijiccj kvemj eidnus disnrst rcconm bcjrof tpzhdo ncxc yjws jnmdmty. Dkmiwza ibudbufrnh ndmcpz tomdyh oqoonsn jhoy rueieihtt vsrjpudcm sotfqsfyv mjeat shnqmslfo oirnzu cru qmpt ggvgxwv jbu kjde. Kzegfq kigj dtzdd ngtytgm comwwoox fgtee ywdrnbam utu nyvlyiv tubouw lezpkmyq fkoa jlygdgf pgv gyerges wbykcxhwe bcpmt beqtkq. Mfxcqyh vhvpovktvl hrmsgfxnt jmnhyndk qohnlmgc sicmlnsq nwku dxtbmwrta omikpmajv qda qrn cwoyfaykxa xqnbv bwbnyov hbrskzt. Pdfqwzpb hypvtknt bovxx noramu xhzam kfb ympmebhqxw gbtaszonqo zmsdgcku mjkjc widrymjzj nytudruhfr uudsitbst cgmwewxpi bye. Eyseox wyef ikdnws weoyof dqecfwokkv svyjdyulk glusauosnu achmrakky kdcfp kujrqcq xojqbxrp mpfv vmw tahxtnw fhe lcitj."
    Random.paragraph(2)
    // => "Dlpec hnwvovvnq slfehkf zimy qpxqgy vwrbi mok wozddpol umkek nffjcmk gnqhhvm ztqkvjm kvukg dqubvqn xqbmoda. Vdkceijr fhhyemx hgkruvxuvr kuez wmkfv lusfksuj oewvvf cyw tfpo jswpseupm ypybap kwbofwg uuwn rvoxti ydpeeerf."
    Random.paragraph(1, 3)
    // => "Qdgfqm puhxle twi lbeqjqfi bcxeeecu pqeqr srsx tjlnew oqtqx zhxhkvq pnjns eblxhzzta hifj csvndh ylechtyu."

    Random.cparagraph( min?, max? )

    . Random.cparagraph()
    . Random.cparagraph( len )
    . Random.cparagraph( min, max )
    随机生成一段中文文本。

    参数的含义和默认值同 Random.paragraph( min?, max? ))

    1
    2
    3
    4
    5
    6
    7
    8
    Random.cparagraph()
    // => "给日数时化周作少情者美制论。到先争劳今已美变江以好较正新深。族国般建难出就金感基酸转。任部四那响成族利标铁导术一或已于。省元切世权往着路积会其区素白思断。加把他位间存定国工取除许热规先法方。"
    Random.cparagraph(2)
    // => "去话起时为无子议气根复即传月广。题林里油步不约认山形两标命导社干。"
    Random.cparagraph(1, 3)
    // => "候无部社心性有构员其深例矿取民为。须被亲需报每完认支这明复几下在铁需连。省备可离展五斗器就石正队除解动。"

    Random.sentence( min?, max? )

    . Random.sentence()
    . Random.sentence( len )
    . Random.sentence( min, max )
    随机生成一个句子,第一个单词的首字母大写。

    len

    指示句子中单词的个数。默认值为 12 到 18 之间的随机数。

    min

    指示句子中单词的最小个数。默认值为 12。

    max

    指示句子中单词的最大个数。默认值为 18。

    1
    2
    3
    4
    5
    6
    Random.sentence()
    // => "Jovasojt qopupwh plciewh dryir zsqsvlkga yeam."
    Random.sentence(5)
    // => "Fwlymyyw htccsrgdk rgemfpyt cffydvvpc ycgvno."
    Random.sentence(3, 5)
    // => "Mgl qhrprwkhb etvwfbixm jbqmg."

    Random.csentence( min?, max? )

    . Random.csentence()
    . Random.csentence( len )
    . Random.csentence( min, max )
    随机生成一段中文文本。

    参数的含义和默认值同 Random.sentence( min?, max? ))

    1
    2
    3
    4
    5
    6
    7
    8
    Random.csentence()
    // => "第任人九同段形位第律认得。"
    Random.csentence(2)
    // => "维总。"
    Random.csentence(1, 3)
    // => "厂存。"

    Random.word( min?, max? )

    . Random.word()
    . Random.word( len )
    . Random.word( min, max )
    随机生成一个单词。

    len

    指示单词中字符的个数。默认值为 3 到 10 之间的随机数。

    min

    指示单词中字符的最小个数。默认值为 3。

    max

    指示单词中字符的最大个数。默认值为 10。

    1
    2
    3
    4
    5
    6
    7
    Random.word()
    // => "fxpocl"
    Random.word(5)
    // => "xfqjb"
    Random.word(3, 5)
    // => "kemh"
    目前单词中的字符是随机的小写字母,未来会根据词法生成『可读』的单词。

    Random.cword( pool?, min?, max? )

    . Random.cword()
    . Random.cword( pool )
    . Random.cword( length )
    . Random.cword( pool, length )
    . Random.cword( min, max )
    . Random.cword( pool, min, max )
    随机生成一个汉字。

    pool

    汉字字符串。表示汉字字符池,将从中选择一个汉字字符返回。

    min

    随机汉字字符串的最小长度。默认值为 1。

    max

    随机汉字字符串的最大长度。默认值为 1。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    Random.cword()
    // => "干"
    Random.cword('零一二三四五六七八九十')
    // => "六"
    Random.cword(3)
    // => "别金提"
    Random.cword('零一二三四五六七八九十', 3)
    // => ""七七七""
    Random.cword(5, 7)
    // => "设过证全争听"
    Random.cword('零一二三四五六七八九十', 5, 7)
    // => "九七七零四"

    Random.title( min?, max? )

    . Random.title()
    . Random.title( len )
    . Random.title( min, max )
    随机生成一句标题,其中每个单词的首字母大写。

    len

    指示单词中字符的个数。默认值为 3 到 7 之间的随机数。

    min

    指示单词中字符的最小个数。默认值为 3。

    max

    指示单词中字符的最大个数。默认值为 7。

    1
    2
    3
    4
    5
    6
    Random.title()
    // => "Rduqzr Muwlmmlg Siekwvo Ktn Nkl Orn"
    Random.title(5)
    // => "Ahknzf Btpehy Xmpc Gonehbnsm Mecfec"
    Random.title(3, 5)
    // => "Hvjexiondr Pyickubll Owlorjvzys Xfnfwbfk"

    Random.ctitle( min?, max? )

    . Random.ctitle()
    . Random.ctitle( len )
    . Random.ctitle( min, max )
    随机生成一句中文标题。

    参数的含义和默认值同 Random.title( min?, max? ))

    len

    指示单词中字符的个数。默认值为 3 到 7 之间的随机数。

    min

    指示单词中字符的最小个数。默认值为 3。

    max

    指示单词中字符的最大个数。默认值为 7。

    1
    2
    3
    4
    5
    6
    Random.ctitle()
    // => "证构动必作"
    Random.ctitle(5)
    // => "应青次影育"
    Random.ctitle(3, 5)
    // => "出料阶相"

    Name

    Random.first()

    . Random.first()
    随机生成一个常见的英文名。

    1
    2
    Random.first()
    // => "Nancy"

    Random.last()

    . Random.last()
    随机生成一个常见的英文姓。

    1
    2
    Random.last()
    // => "Martinez"

    Random.name( middle? )

    . Random.name()
    . Random.name( middle )
    随机生成一个常见的英文姓名。

    middle

    布尔值。指示是否生成中间名。

    1
    2
    3
    4
    Random.name()
    // => "Larry Wilson"
    Random.name(true)
    // => "Helen Carol Martinez"

    Random.cfirst()

    . Random.cfirst()
    随机生成一个常见的中文名。

    1
    2
    Random.cfirst()
    // => "曹"

    Random.clast()

    . Random.clast()
    随机生成一个常见的中文姓。

    1
    2
    Random.clast()
    // => "艳"

    Random.cname()

    . Random.cname()
    随机生成一个常见的中文姓名。

    1
    2
    Random.cname()
    // => "袁军"

    Web

    Random.url( protocol?, host? )

    . Random.url()
    . Random.url( protocol, host )
    随机生成一个 URL。

    protocol

    指定 URL 协议。例如 http。

    host

    指定 URL 域名和端口号。例如 nuysoft.com。

    1
    2
    3
    4
    5
    6
    Random.url()
    // => "mid://axmg.bg/bhyq"
    Random.url('http')
    // => "http://splap.yu/qxzkyoubp"
    Random.url('http', 'nuysoft.com')
    // => "http://nuysoft.com/ewacecjhe"

    Random.protocol()

    . Random.protocol()
    随机生成一个 URL 协议。返回以下值之一:’http’、’ftp’、’gopher’、’mailto’、’mid’、’cid’、’news’、’nntp’、’prospero’、’telnet’、’rlogin’、’tn3270’、’wais’。

    1
    2
    Random.protocol()
    // => "ftp"

    Random.domain()

    . Random.domain()
    随机生成一个域名。

    1
    2
    Random.domain()
    // => "kozfnb.org"

    Random.tld()

    . Random.tld()
    随机生成一个顶级域名(Top Level Domain)。

    1
    2
    Random.tld()
    // => "net"

    Random.email( domain? )

    . Random.email()
    . Random.email( domain )
    随机生成一个邮件地址。

    domain

    指定邮件地址的域名。例如 nuysoft.com。

    1
    2
    3
    4
    Random.email()
    // => "x.davis@jackson.edu"
    Random.email('nuysoft.com')
    // => "h.pqpneix@nuysoft.com"

    Random.ip()

    . Random.ip()
    随机生成一个 IP 地址。

    1
    2
    Random.ip()
    // => "34.206.109.169"

    Address

    Random.region()

    . Random.region()
    随机生成一个(中国)大区。

    1
    2
    Random.region()
    // => "华北"

    Random.province()

    . Random.province()
    随机生成一个(中国)省(或直辖市、自治区、特别行政区)。

    1
    2
    Random.province()
    // => "黑龙江省"

    Random.city( prefix? )

    . Random.city()
    . Random.city( prefix )
    随机生成一个(中国)市。

    prefix

    布尔值。指示是否生成所属的省。

    1
    2
    3
    4
    Random.city()
    // => "唐山市"
    Random.city(true)
    // => "福建省 漳州市"

    Random.county( prefix? )

    . Random.county()
    . Random.county( prefix )
    随机生成一个(中国)县。

    prefix

    布尔值。指示是否生成所属的省、市。

    1
    2
    3
    4
    Random.county()
    // => "上杭县"
    Random.county(true)
    // => "甘肃省 白银市 会宁县"

    Random.zip()

    . Random.zip()
    随机生成一个邮政编码(六位数字)。

    1
    2
    Random.zip()
    // => "908812"

    Helper

    Random.capitalize( word )

    . Random.capitalize(word)
    把字符串的第一个字母转换为大写。

    1
    2
    Random.capitalize('hello')
    // => "Hello"

    Random.upper( str )

    . Random.upper( str )
    把字符串转换为大写。

    1
    2
    Random.upper('hello')
    // => "HELLO"

    Random.lower( str )

    . Random.lower( str )
    把字符串转换为小写。

    1
    2
    Random.lower('HELLO')
    // => "hello"

    Random.pick( arr )

    . Random.pick( arr )
    从数组中随机选取一个元素,并返回。

    1
    2
    Random.pick(['a', 'e', 'i', 'o', 'u'])
    // => "o"

    Random.shuffle( arr )

    . Random.shuffle( arr )
    打乱数组中元素的顺序,并返回。

    1
    2
    Random.shuffle(['a', 'e', 'i', 'o', 'u'])
    // => ["o", "u", "e", "i", "a"]

    Miscellaneous

    Random.guid()

    . Random.guid()
    随机生成一个 GUID。

    1
    2
    3
    Random.guid()
    // => "662C63B4-FD43-66F4-3328-C54E3FF0D56E"
    Random.guid() 的实现参考了 UUID 规范。

    Random.id()

    . Random.id()
    随机生成一个 18 位身份证。

    1
    2
    Random.id()
    // => "420000200710091854"

    Random.increment( step? )

    . Random.increment()
    . Random.increment( step )
    生成一个全局的自增整数。

    step

    整数自增的步长。默认值为 1。

    1
    2
    3
    4
    5
    6
    Random.increment()
    // => 1
    Random.increment(100)
    // => 101
    Random.increment(1000)
    // => 1101

    Mock.valid()

    Mock.valid( template, data )

    . Mock.valid( template, data )
    校验真实数据 data 是否与数据模板 template 匹配。

    template

    表示数据模板,可以是对象或字符串。例如 { ‘list|1-10’:[{}] }、’@EMAIL’。

    data

    表示真实数据。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    var template = {
    name: 'value1'
    }
    var data = {
    name: 'value2'
    }
    Mock.valid(template, data)
    // =>
    [
    {
    "path": [
    "data",
    "name"
    ],
    "type": "value",
    "actual": "value2",
    "expected": "value1",
    "action": "equal to",
    "message": "[VALUE] Expect ROOT.name'value is equal to value1, but is value2"
    }
    ]

    Mock.toJSONSchema()

    Mock.toJSONSchema( template )

    . Mock.toJSONSchema( template )
    把 Mock.js 风格的数据模板 template 转换成 JSON Schema。

    template

    表示数据模板,可以是对象或字符串。例如` { 'list|1-10':[{}] }'@EMAIL'

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    var template = {
    'key|1-10': '★'
    }
    Mock.toJSONSchema(template)
    // =>
    {
    "name": undefined,
    "path": [
    "ROOT"
    ],
    "type": "object",
    "template": {
    "key|1-10": "★"
    },
    "rule": {},
    "properties": [{
    "name": "key",
    "path": [
    "ROOT",
    "key"
    ],
    "type": "string",
    "template": "★",
    "rule": {
    "parameters": ["key|1-10", "key", null, "1-10", null],
    "range": ["1-10", "1", "10"],
    "min": 1,
    "max": 10,
    "count": 3,
    "decimal": undefined,
    "dmin": undefined,
    "dmax": undefined,
    "dcount": undefined
    }
    }]
    }

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    var template = {
    'list|1-10': [{}]
    }
    Mock.toJSONSchema(template)
    // =>
    {
    "name": undefined,
    "path": ["ROOT"],
    "type": "object",
    "template": {
    "list|1-10": [{}]
    },
    "rule": {},
    "properties": [{
    "name": "list",
    "path": ["ROOT", "list"],
    "type": "array",
    "template": [{}],
    "rule": {
    "parameters": ["list|1-10", "list", null, "1-10", null],
    "range": ["1-10", "1", "10"],
    "min": 1,
    "max": 10,
    "count": 6,
    "decimal": undefined,
    "dmin": undefined,
    "dmax": undefined,
    "dcount": undefined
    },
    "items": [{
    "name": 0,
    "path": ["data", "list", 0],
    "type": "object",
    "template": {},
    "rule": {},
    "properties": []
    }]
    }]
    }