在弄清楚如何在工厂测试 $http 请求时遇到问题。
基础工厂:
angular.module('myServices', [])
.factory('myFactory', function($http) {
return {
postLog: function(logData) {
logData.newProperty = 'my new property';
return $http.post('/log', logData);
};
};
});
现在我想测试一下以确保我添加了我的newProperty
. 我希望能够编写如下测试:
it('adds a new property before POSTing', function() {
MyFactory.postLog({message: 'posting a log!'});
// catch the request somehow
expect(theRequest.data).to.have.property('newProperty');
});
我最初的想法是这样$httpBackend.expect
可以让我访问请求,但它似乎只有一个.respond
方法,没有别的:
var MyFactory, backend;
beforeEach(function() {
module('exampleApp');
inject(function($httpBackend, _myFactory_) {
backend = $httpBackend;
backend.expect('POST', '/log').??? // would be nice to have a `.request` method here or a parameter passed to `.respond`
MyFactory = _myFactory_;
});
});
所以我尝试httpInterceptor
通过执行以下操作来设置:
var MyFactory, theRequest;
beforeEach(function() {
module('exampleApp', function($provide, $httpProvider) {
$provide.service('requestCatcher', function() {
this.request = function(req) {
console.log(req);
request = req;
return req;
};
});
$httpProvider.interceptors.push('requestCatcher');
});
inject(function(_myFactory_) {
MyFactory = _myFactory_;
});
});
it('adds a new property before POSTing', function() {
MyFactory.postLog({message: 'posting a log!'});
expect(theRequest.data).to.have.property('newProperty');
});
但拦截器从未真正触发(日志不会打印到日志中)。我对这个有点想法。
也许我在postLog
方法中添加新属性违反了某些原则,应该将其重构为自己的可测试性方法?尽管如此,如果有一种方法可以利用出站请求,即使它会被$httpBackend.expect
.