在当前前后端普遍分离的情况下,前端和后端开发节奏肯定无法保持高度一致性,这样就会造成前端开发要等后台人员接口开发完之后才能继续开发下去。为了避免这种现象,在今年年初的时候,就让团队去引入阿里Mock数据工具,但是实际上引入过程发现水土不服,后面也就不了了之了。最近,有人提出使用Mock.js,本人亲测了一下,简单好用,能够适应多人多项目使用,就去专门看了文档,写了一些例子,与君共勉。
首先我上传一下Mock.js知识思维导图如下图。
这里我们可以看到Mock.js主要分两大部分,第一部分是语法规范,第二部分是方法库,接下来我们一个个来看。
一、语法部分
先看下语法规范导图
1.数据模板定义规范
生成‘name’数据,重复1-n次
var data = Mock.mock({
// 属性 list 的值是一个数组,其中含有 1 到 10 个元素
'list|1-10': [{
// 属性 id 是一个自增数,起始值为 1,每次增 1
'id|1-10': 'linjian'
}]
})
console.log(data)
结果:
{ list:
[ { id: 'linjianlinjian' },
{ id: 'linjianlinjianlinjian' },
{ id: 'linjianlinjianlinjian' },
{ id: 'linjianlinjianlinjianlinjianlinjian' },
{ id: 'linjianlinjianlinjianlinjianlinjianlinjianlinjian' },
{ id: 'linjianlinjianlinjianlinjianlinjianlinjian' } ] }
2.生成一个大于等于 min、小于等于 max 的整数,属性值 number 只是用来确定类型。
var data = Mock.mock({
// 属性 list 的值是一个数组,其中含有 1 到 10 个元素
'list|1-10': [{
// 属性 id 是一个自增数,起始值为 1,每次增 1
'id|1.2-10.4': 1
}]
})
结果:
{ list:
[ { 'id.4': 1.13567 },
{ 'id.4': 1.5622 },
{ 'id.4': 1.71756852 },
{ 'id.4': 1.8666 },
{ 'id.4': 1.78857 },
{ 'id.4': 1.6282762174 },
{ 'id.4': 1.5688965 },
{ 'id.4': 1.56767113 },
{ 'id.4': 1.629029 } ] }
3.随机生成Boolean值
var data = Mock.mock({
// 属性 list 的值是一个数组,其中含有 1 到 10 个元素
'list|1-10': [{
// 属性 id 是一个自增数,起始值为 1,每次增 1
'id|1-10': true
}]
})
console.log(data)
结果:
{ list:
[ { id: false },
{ id: false },
{ id: false },
{ id: false },
{ id: false },
{ id: false },
{ id: false },
{ id: true },
{ id: false } ] }
4.从属性值 object 中随机选取 count 或者min-max个属性。
var data = Mock.mock({
'list|1-10':{'name':'linjian','age':15,'job':'it','favior':'no thing','book':'any'}
})
console.log(data)
结果:
{ list:
{ job: 'it',
name: 'linjian',
favior: 'no thing',
book: 'any',
age: 15 } }
{ list:
{ age: 15,
book: 'any',
favior: 'no thing',
name: 'linjian',
job: 'it' } }
5.通过重复属性值 array 生成一个新数组,重复次数大于等于 min,小于等于 max
var Mock = require('mockjs')
var Random = Mock.Random;
var data = Mock.mock({
//'list|1-10':{'name':'linjian','age':15,'job':'it','favior':'no thing','book':'any'}
'item|1-10':[
{
'name':Random.cname(),
'age':Random.natural(10,40),
'email':Random.email(),
'Address':Random.province()+Random.city(true)+Random.county(true),
'book':'any'}
]
})
console.log(data)
结果:
{ item:
[ { name: '郭娟',
age: 30,
email: '[email protected]',
Address: '黑龙江省山东省 威海市江苏省 盐城市 盐都区',
book: 'any' },
{ name: '郭娟',
age: 30,
email: '[email protected]',
Address: '黑龙江省山东省 威海市江苏省 盐城市 盐都区',
book: 'any' },
{ name: '郭娟',
age: 30,
email: '[email protected]',
Address: '黑龙江省山东省 威海市江苏省 盐城市 盐都区',
book: 'any' },
{ name: '郭娟',
age: 30,
email: '[email protected]',
Address: '黑龙江省山东省 威海市江苏省 盐城市 盐都区',
book: 'any' },
{ name: '郭娟',
age: 30,
email: '[email protected]',
Address: '黑龙江省山东省 威海市江苏省 盐城市 盐都区',
book: 'any' },
{ name: '郭娟',
age: 30,
email: '[email protected]',
Address: '黑龙江省山东省 威海市江苏省 盐城市 盐都区',
book: 'any' },
{ name: '郭娟',
age: 30,
email: '[email protected]',
Address: '黑龙江省山东省 威海市江苏省 盐城市 盐都区',
book: 'any' },
{ name: '郭娟',
age: 30,
email: '[email protected]',
Address: '黑龙江省山东省 威海市江苏省 盐城市 盐都区',
book: 'any' },
{ name: '郭娟',
age: 30,
email: '[email protected]',
Address: '黑龙江省山东省 威海市江苏省 盐城市 盐都区',
book: 'any' },
{ name: '郭娟',
age: 30,
email: '[email protected]',
Address: '黑龙江省山东省 威海市江苏省 盐城市 盐都区',
book: 'any' } ] }
6.匹配正则表达式
var Random = Mock.Random;
var data = Mock.mock({
'regexp1': /[a-z][A-Z][0-9]/,
'regexp2': /\w\W\s\S\d\D/,
'regexp3': /\d{5,10}/
})
console.log(data)
结果是:
{ regexp1: 'rY0', regexp2: 'F#\tt7Y', regexp3: '35318701' }
二、Mock.mock
先看下思维导图
我们可以看出mock就是模拟数据和拦截请求。
1.拦截Ajax请求
Mock.mock(/\.json/, {
'list|1-10': [{
'id|+1': 1,
'email': '@EMAIL'
}]
})
$.ajax({
url: 'hello.json',
dataType: 'json'
}).done(function(data, status, jqXHR){
$('').text(JSON.stringify(data, null, 4))
.appendTo('body')
})
结果:
{
"list": [
{
"id": 1,
"email": "[email protected]"
},
{
"id": 2,
"email": "[email protected]"
},
{
"id": 3,
"email": "[email protected]"
},
{
"id": 4,
"email": "[email protected]"
},
{
"id": 5,
"email": "[email protected]"
},
{
"id": 6,
"email": "[email protected]"
}
]
}
三、Mock.setup(setting)
1.设置请求超时时间
Mock.setup({
timeout: '200-600'
})
四、Mock.Random
这是一个工具类,用于生成各种数据,具体可以参考文档,Api比较多且全
五、现在我们写一个列子
生成数据格式如下所示的
{
"kdjson": {
"flag": "1",
"msg": "查询成功",
"timeSpent": 0,
"code": "0",
"detail": "koauth2v4liqing-0ac93e25-418547-25",
"len": 6,
"lengths": 49,
"items": [
{
"isSync": "0",
"beginOption": "3",
"ROWSCOUNT": 49,
"product_name_new": "0928-90940010多经纪商-01期-自营",
"receiptsCalTypeText": "预期收益",
"investorVol": 6,
"transDjs": -302456,
"subStartDesc": "1000,2000",
"productType": "1",
"interestType": "3",
"cat_id": "c201708300951032219",
"benefitDesc": "",
"checkStatus": "1",
"deadLineUnit": "M",
"receiptsCalType": "5",
"productStatus": "2",
"raiseTerm": 1,
"transTime": 20170929100300,
"deadLineUnitText": "月",
"bondAmount": 12000.00,
"annualrateDesc": "",
"ytinvestorVol": 0,
"loanerId": "1354",
"leftDays": 0,
"firstCatName": "债券分类",
"productCodeNew": "2017092817343107224",
"productCode": "B201709281605558222",
"bondInvestAmount": 0.00,
"repayType": "6",
"interestTypeText": "按月计息",
"isfull": "0",
"isoverdue": 1,
"ipoStartDate": 20170928160015,
"isTrans": "1",
"deadLine": 3,
"subStartPerson": 1000,
"onTime": 20170929100208,
"subStartOrg": 2000,
"ipoDjs": -367421,
"productTag": null,
"isCheckInvestorNum": "1",
"isbuyerfull": "0",
"expireDate": 20171229,
"annualrate": 3.8900,
"repayTypeText": "等额本金",
"productName": "0928-90940010多经纪商-01期"
}
],
"api": "kingdom.ktrade.get_pif_bonds_sub_list@1506953036473",
"time": "120ms"
}
}
这种情况我们可以写一个template来完成
var template1 = {
"kdjson": {
"flag|1": ["1","0"],
"msg": function(){
if(this.flag ==='1'){
return "查询成功"
}else{
return "查询失败"
}
},
"timeSpent": 0,
"code": "0",
"detail": "koauth2"+Random.guid(),
"items|1-10": [
{
"isSync|1": ["0","1"],
"beginOption|1": ["3","4","5"],
"ROWSCOUNT|1": [Random.integer(1,200),Random.integer(1,200),Random.integer(1,200),Random.integer(1,200)],
"product_name_new|1": [Random.ctitle(1,10),Random.ctitle(1,10),Random.ctitle(1,10)],
"receiptsCalTypeText": "预期收益",
"investorVol|1": [6,Random.natural(1,200),Random.natural(1,200),Random.natural(1,200)],
"transDjs|1": [Random.integer(-10000,0),Random.integer(-10000,0),Random.integer(-10000,0)],
"subStartDesc": "1000,2000",
"productType|1": ["1","2","3"],
"interestType": "3",
"cat_id|1": ["c201708300951032219",'c'+Random.guid(),'c'+Random.guid()],
"benefitDesc|1": [Random.cparagraph(1,5),Random.cparagraph(1,5),Random.cparagraph(1,5)],
"checkStatus": "1",
"deadLineUnit|1": ["M","Y","D"],
"receiptsCalType": "5",
"productStatus": "2",
"raiseTerm": 1,
"transTime": 20170929100300,
"deadLineUnitText": function(){
if(this.deadLineUnit === 'Y'){
return '年'
}else if(this.deadLineUnit === 'M'){
return '月'
}else{
return '日'
}
},
"bondAmount|100-1000000.1-4": 1,
"annualrateDesc|1": [Random.cparagraph(1,5),Random.cparagraph(1,5),Random.cparagraph(1,5)],
"ytinvestorVol": 0,
"loanerId": "1354",
"leftDays": 0,
"firstCatName": "债券分类",
"productCodeNew|1": [Random.datetime('YYYYMMddHHmmss'),Random.datetime('YYYYMMddHHmmss'),Random.datetime('YYYYMMddHHmmss')]
}
],
"api": "kingdom.ktrade.get_pif_bonds_sub_list@1506953036473",
"time": "120ms"
}
}
var data = Mock.mock(template1)
生成结果:
{
"kdjson": {
"flag": "0",
"timeSpent": 0,
"code": "0",
"detail": "koauth2B6D3c33C-d1Ce-D8A2-bD66-a11FbBdb81cC",
"items": [
{
"isSync": "1",
"beginOption": "4",
"ROWSCOUNT": 38,
"product_name_new": "八格价般行达称其速二",
"receiptsCalTypeText": "预期收益",
"investorVol": 6,
"transDjs": -1362,
"subStartDesc": "1000,2000",
"productType": "3",
"interestType": "3",
"cat_id": "c30dF22bE-dD99-b4d6-c4aE-6F6AbFb709Da",
"benefitDesc": "称眼越根革细用增引县近又。广清张政较声将色统细叫团报维处适容。养直青查近类算政却指工五区温。以常热科命到儿劳识存飞条过看采计。小定算则究想布干铁产管引种不。",
"checkStatus": "1",
"deadLineUnit": "M",
"receiptsCalType": "5",
"productStatus": "2",
"raiseTerm": 1,
"transTime": 20170929100300,
"bondAmount": 116399.55,
"annualrateDesc": "政什只说少效张率子属数几复那备斗。期后志导门海例因次而集半或道得低。参圆五山照造联集内集子市工装保织性。",
"ytinvestorVol": 0,
"loanerId": "1354",
"leftDays": 0,
"firstCatName": "债券分类",
"productCodeNew": [
"YYYY1213030543",
"YYYY0512180018",
"YYYY0425091159"
],
"deadLineUnitText": "月"
},
{
"isSync": "1",
"beginOption": "4",
"ROWSCOUNT": 92,
"product_name_new": "叫民向给时市活",
"receiptsCalTypeText": "预期收益",
"investorVol": 6,
"transDjs": -1362,
"subStartDesc": "1000,2000",
"productType": "3",
"interestType": "3",
"cat_id": "cE49F8dF8-1CbD-8D17-ebcD-3bB6188DA2CC",
"benefitDesc": "第些气型立两管片米高影导满常三度。毛活金家飞看口低育员义如南按向认明。想想称不可色集关广织到界流众世次党。",
"checkStatus": "1",
"deadLineUnit": "M",
"receiptsCalType": "5",
"productStatus": "2",
"raiseTerm": 1,
"transTime": 20170929100300,
"bondAmount": 243040.2,
"annualrateDesc": "而长山过称她低达存切向我火。又如例属值实道不会传际别与农别。率中直打维济今成行界第变我。铁少还革先门将而严不些听头非。志结区快个后设率严需比选其引。",
"ytinvestorVol": 0,
"loanerId": "1354",
"leftDays": 0,
"firstCatName": "债券分类",
"productCodeNew": [
"YYYY1213030543",
"YYYY0512180018",
"YYYY0425091159"
],
"deadLineUnitText": "月"
}
],
"api": "kingdom.ktrade.get_pif_bonds_sub_list@1506953036473",
"time": "120ms",
"msg": "查询失败"
}
}
最后,我上传一下思维导图