Mock文档

1. 语法规范 Syntax Specification

  1. 数据模板定义规范 Data Template Defination
  2. 数据占位符定义规范 Data Placeholder Defination
  • 模板中的属性由3部分组成:属性名 name、生成规则 rule、属性值 value
    • 'name|rule': value
    • rule的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
  • 生成规则
    • String
    • Number
    • Boolean
    • Object
    • Array
    • Function
    • RegExp
  • 占位符用 @ 引用

2. Mock.mock()

Mock.mock(requestUrl, requestType, responseFunction | responseTemplate)

3. Mock.setup()

Mock.setup(settings) 配置拦截Ajax请求时的行为

  • timeout 响应事件ms
  • Mock.setup({timeout: 400})
  • Mock.setup({timeout: '200-600'})

4. Mock.Random()

var Random = Mock.Random
Random.email()
Mock.mock('@email')
Mock.mock({email: '@email'})
  • Random提供的完整方法
    • Basic
      • boolean
      • natural,integer,float
      • character
        • 字符池 ‘lower’,‘upper’,‘number’,‘symbol’
      • string,range,date,time,datetime,now
    • Image
      • image,dataImage
    • Color
      • color
    • Text
      • paragraph,sentence,word,title,cparagraph,csentence,cword,ctitle
    • Name
      • first,last,name,cfirst,clast,cname
    • Web
      • url,domain,email,ip,tld
    • Address
      • area,region,province,
      • city(true),county(prefix)是否前缀
      • zip邮政编码
    • Helper
      • capitalize大写首字母
      • upper,lower全部大小写
      • pick随机选取一个
      • shuffle打乱顺序并返回
    • Miscellaneous 混杂,其他
      • guid,id
  • 自己扩展
Random.extend({
	constellation: function(date){
		var constellations = ['白羊座', ...];
		return this.pick(constellations)
	}
})

Random.constellation();
Mock.mock('@constellation');

5. Mock.valid()

验证模板与真实数据

Mock.valid(template, data);

6. Mock.toJSONSchema()

把mock风格的数据模板转换成JSON Schema

Mock.toJSONSchema(template);

7. Vue中使用Mock

// mock/index.js
var Mock = require('mockjs');
var Random = Mock.Random;

Mock.mock('/api/users', 'get', {
	'users|2-5': [{
		'id|+1': 1,
		'name': '@cname'
	}]
})

// main.js
require('./mock');

// vue
axios.get('/api/users').then(response => {
	console.log(response.data);
})
//{"users":[{"id":1,"name":"马平"},{"id":2,"name":"龚娜"},{"id":3,"name":"高娟"}]}