我有一个针对restful API的AngularJS服务:
angular
.module('app', [
])
.service('api', ['$http', '$q', function APIService($http, $q) {
this.get = function (dataProperty, params) {
return $http({
method: 'get',
url: 'https://some.api/rest/',
params: angular.extend({
default_params...
}, params)
})
.then(
function (result) {
if (result.data.status === 'ok') {
return result.data[dataProperty];
} else {
return $q.reject(angular.extend(new Error(result.data.message), { result: result.data }));
}
},
function (reason) {
return $q.reject(angular.extend(new Error('AJAX request to the API failed'), { reason: reason.data }));
});
};
}]);
我正在尝试使用以下内容测试此api.get:
describe('api', function () {
var
$httpBackend,
service;
beforeEach(module('app'));
beforeEach(inject(function (_$httpBackend_, _api_) {
$httpBackend = _$httpBackend_;
service = _api_;
}));
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('', function () {
$httpBackend
.when('get', 'https://some.api/rest/')
.respond({
data: {
status: 'ok'
}
});
service.get('status', {});
$httpBackend.flush();
$httpBackend
.expect('get', 'https://some.api/rest/');
});
});
但我每次都会收到错误回调:
Error: AJAX request to the API failed in bower_components/angular-mocks/angular-mocks.js (line 279)
我是否正确设置测试?我相信.when
和.response
用于伪造实际的$ http调用,但我无法触发成功回调。
答案 0 :(得分:0)
这两个问题.when
没有找到正确的网址(因为我需要将params投入使用才能使其成为正则表达式:
.when('GET', /https:\/\/api\.flickr\.com\/services\/rest\/.*/)
然后,.respond
不需要用数据对象填充,它会为你做到:
.respond({ stat: 'ok' });