我有一个服务,其中包含用于进行异步API调用的代码:
myApp.factory('ConcernService', function ($http, $q, $rootScope, dateFilter, globals) {
var api_url = 'http://' + globals.site_url + '/api/';
var ConcernService = {
list: function (items_url) {
var defer = $q.defer();
$http({method: 'GET',
url: api_url + items_url}).
success(function (data, status, headers, config) {
defer.resolve(data);
}).error(function (data, status, headers, config) {
defer.reject(status);
});
return defer.promise;
},
...
};
});
我正在尝试为这种方法编写一个Jasmine测试,但由于我是Angular和Jasmine的新手,因此它证明是棘手的。
到目前为止,我的测试看起来如此:
describe('$http basic', function () {
var $http, $httpBackend, $scope;
beforeEach(module('concernsApp'));
beforeEach(inject(function (_ConcernService_, _$http_, _$httpBackend_) {
ConcernService = _ConcernService_;
$http = _$http_;
$httpBackend = _$httpBackend_;
}));
it('should return all projects', function () {
var projects = [{"id": 2, "title": "FooProject", "created_by": 1}, {"id": 5, "title": "BarProject", "created_by": 1}];
$httpBackend.whenGET('http://localhost:8000/api/projects/')
.respond(projects);
ConcernService.list('projects')
.then(function(data) {
console.log('data', data);
expect(data.length).toEqual(2);
});
$httpBackend.flush();
});
});
这是失败的,但我不完全确定原因。
答案 0 :(得分:1)
因此,事实证明错误是因为使用了promises,这意味着需要在apply()
之前使用$httpBackend.flush();
方法。正如JB Nizet正确指出的那样,我也在我的网址结构中存在一个不一致的地方,当最初的问题得到解决时,它就会显露出来。
工作代码:
describe('$http basic', function () {
var $http, $httpBackend, $scope;
beforeEach(module('concernsApp'));
beforeEach(inject(function ($rootScope, _ConcernService_, _$httpBackend_) {
ConcernService = _ConcernService_;
$httpBackend = _$httpBackend_;
$scope = $rootScope.$new();
}));
it('should return all projects', function () {
var projects = [{"id": 2, "title": "FooProject", "created_by": 1}, {"id": 5, "title": "BarProject", "created_by": 1}];
$httpBackend.whenGET('http://localhost:8000/api/projects')
.respond(projects);
ConcernService.list('projects')
.then(function(data) {
expect(data.length).toEqual(2);
});
$scope.$apply();
$httpBackend.flush();
});
});