angular-mocks
前后端分离的开发模式中, 为了能让前端不依赖后端服务而能够并行开发, angular-mocks能模拟一些后台返回的数据,从而使前端看起来已经跟后端对接了一样, 只要与后端商定好数据格式, 自己mock一些数据就能够对前端功能进行测试了.
1. 安装
bower install angular-mocks@X.Y.Z
(X、Y、Z为你需要的AngularJS版本号。)
2. 引入
在angular启动模块中引入ngMockE2E模块
angular.module('myApp', [
'ngMockE2E',
'myApp.mock'
])
其中, ‘myApp.mock’是自定义的用来mock数据的模块.
3. 使用
‘myApp.mock’模块:
angular.module('myApp.mock', [])
.run(["$httpBackend", "$rootScope", "$http",
function ($httpBackend, $rootScope, $http) {
//对于html模板的请求不拦截
$httpBackend.whenGET(/views\/(.+).html/).passThrough();
$httpBackend.whenPOST(/\/meta\/module\/config\/delete/).respond(200, {
"success": true,
"code": 200,
"message": "",
"data": "1"
});
});
上面代码中用到了两个方法:’whenGet’和’whenPost’,分别用于处理get和post请求, 事实上可以理解为这两个方法都是继承自when方法:
$httpBackend.when = function(method, url, data, headers, keys)
‘whenGet’和’whenPost’只是给参数method设置了默认值, 从when方法中可以看出, 它允许你指定以什么方式(method),带着什么请求头(headers) 向哪个url(url)发送了什么数据(data), keys接受一个数组, 用于跟url进行正则匹配.
接下来链式调用一个方法respond(), 用于设置希望返回的数据.
chain = {
respond: function(status, data, headers, statusText) {
definition.passThrough = undefined;
definition.response = createResponse(status, data, headers, statusText);
return chain;
}
};
从方法定义中可以看出能够为返回数据指定状态码, 数据实体, 返回头, 以及状态文本.
定义好’myApp.mock’模块之后, 发请求的时候就会被angular-mock拦截, 若定义了被请求的url返回数据, 则会正常返回, 未定义则会抛出异常:
Error: Unexpected request: GET views/base/base.html(…) "Possibly unhandled rejection: {}"