mock.js can simulate ajax data, intercept ajax request, return the analog data, without having to return to the rear end of the front end of the program can be tested
Original: HTTP: //i.jakeyu.top/2016/08/1 ...
First, we need to introduce mockjs file header in the head
<script src="http://mockjs.com/dist/mock.js"></script>
Before ajax request returns data defined mack
Mock.mock('http://laoyu', {
"errorcode": 0,//0表示成功,1表示错误
"message": "xx信息不完整", //弹出错误信息
});
In ajax, we should mock in the same open () with the url, like me here http://laoyu
, so
XHR.open("post/get","http://laoyu",true/false)
Well, at this point, we test
<script>
//调用mock方法模拟数据
Mock.mock('http://laoyu', {
"errorcode": 0,//0表示成功,1表示错误
"message": "xx信息不完整", //弹出错误信息
});
//使用ajax进行测试
var xhr = XMLHttpRequest();
xhr.open("post","http://laoyu",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(null);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if((xhr.status>=200 && xhr.status<300) || xhr.status== 304){
var data = JSON.parse(xhr.responseText);
//因为reponseText返回的是字符串,将字符串转换成我们想要的JSON数据,这样就可以调用了
console.log(data); //在控制台中打印出返回的内容
}else{
alert("Request was unsuccessful: " + xhr.status);
}
}
}
</script>
That did not, return the data we use mock simulation, so you may not need the background, the direct conduct their own tests
xhr.readyState of five states
0 - (未初始化)还没有调用open()方法
1 - (服务器连接已经建立)已调用open()方法,正在发送请求
2 - (请求已接收)send()方法执行完成,已经接收到全部响应内容
3 - (请求处理中)正在解析响应内容
4 - (请求已完成)响应内容解析完成,可以在客户端调用了