用处
在前后台共同进行一个项目的时候常会遇到一种情景, 后台定义好接口,前端按照接口进行开发, 当前端开发完成后台接口却还没有开发完成, 这个时候要进行接口测试, 只能等后台开发完成才能测试, 在这中间浪费了很多时间, 现在有个利器可以解决这个问题, 即使不用后台,只要提前制定好接口的报文,那么前端就可以自己模拟接口来进行接口测试了, 今天要讲的东西就是mockjax和mockJSON
简介
mockjax和mockJSON是两套不同的Javascript Library, 它们都是基于JQuery来开发的,
mockjax主要是可以针对指定的网址进行mock, 当Ajax呼叫网址时拦截并回传假的数据,
mockJSON则有点像是Json资料的Data Generater, 根据我们指定的格式随机数生成回传的Json资料.
mockjax官方地址:https://github.com/appendto/jquery-mockjax/
mockJSON官方地址:http://experiments.mennovanslooten.nl/2010/mockjson/
例子
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>Mocking JQuery Ajax</title>
</head>
<body>
<h1>User Data1</h1><div id="result1"></div>
<h1>User Data2</h1><div id="result2"></div>
<h1>User Data3</h1><div id="result3"></div>
</body>
<script src="jquery-1.7.2.js" type="text/javascript"></script>
<script src="jquery.mockjax.js" type="text/javascript"></script>
<script src="jquery.mockjson.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var isAjaxMocked = true;
if (isAjaxMocked) {
$.mockjax({
url: '/WebApi/GetUserData1.svc'+'*',//匹配任意参数
status: 200,
responseTime: 750,
responseText: 'User Information'
});
$.mockjax({
url: '/WebApi/GetUserData2.svc',
status: 200,
responseTime: 750,
responseText: { "user": [{ "id": "1", "name": "david", "birthday": "2001/01/26" }] }
});
$.mockJSON.data.KEY = ['关键词1', '关键词2', '关键词3', '关键词4', '关键词5', '关键词6', '关键词7', '关键词8', '关键词9', '关键词10'];
$.mockjax({
url: '/WebApi/GetUserData3.svc',
status: 200,
responseTime: 750,
responseText: $.mockJSON.generateFromTemplate({//使用mockJSON返回json数据
"user|20-30": [{//user
"id|+1": 1,//id递增
"title": "@KEY ",//从KEY中随机选择
"group|0-1": true,
"park|0-1": 0,
"address": "海南",
"price|100-500": 100//100-500间的随机数
}]
})
});
}
$.ajax({
url: '/WebApi/GetUserData1.svc?ip=null&date=1439827200000',
type: 'GET',
error: function (xhr) {
alert('無法取得資料!');
},
success: function (response) {
$("#result1").append(response);
}
});
$.ajax({
url: '/WebApi/GetUserData2.svc',
type: 'GET',
error: function (xhr) {
alert('無法取得資料!');
},
success: function (response) {
var data = response.user;
for (var i = 0; i < data.length; i++) {
$("#result2").append(
"<ul>" +
"<li>ID: " + data[i].id + "</li>" +
"<li>Name: " + data[i].name + "</li>" +
"<li>Birthday: " + data[i].birthday + "</li>" +
"</ul>" +
"<hr/>"
);
}
}
});
$.ajax({
url: '/WebApi/GetUserData3.svc',
type: 'GET',
error: function (xhr) {
alert('無法取得資料!');
},
success: function (response) {
var data = response.user;
for (var i = 0; i < data.length; i++) {
$("#result3").append(
"<ul>" +
"<li>ID: " + data[i].id + "</li>" +
"<li>title: " + data[i].title + "</li>" +
"<li>group: " + data[i].group + "</li>" +
"<li>park: " + data[i].park + "</li>" +
"<li>address: " + data[i].address + "</li>" +
"<li>price: " + data[i].price + "</li>" +
"</ul>" +
"<hr/>"
);
}
}
});
});
</script>
</html>