我对angularJS很陌生。尝试使用 httpBackend 测试 Angular 服务,但无法使其正常工作。我究竟做错了什么?在 SO 上尝试了其他类似问题的答案,但我得到的最接近的是以下(仍然无法正常工作,xData 未定义):
xApp.services.js
'use strict';
var services = angular.module('xApp.services', []);
services.factory('xService', function ($http, $location) {
var urlPath = $location.path() || 'http://localhost:8000';
var xData;
var getXData = function () {
var promise = $http.get(urlPath + '/xData')
.then(function (res) {
xData = res.data;
return xData;
});
return promise;
};
return {
getXData: getXData
};
});
xServiceSpec.js
describe('xService', function () {
beforeEach(module('xApp.services'));
var $httpBackend;
var xData;
beforeEach(inject(function ($injector) {
$httpBackend = $injector.get('$httpBackend');
$httpBackend.when('GET', '/xData').respond(
{
_id: 25,
name: "TestName",
xarr: [
{
_id: 11,
name: "TestArrName",
created: "2013-09-29"
}
]
}
);
$httpBackend.when('POST', '/newXArr').respond("ok");
}));
beforeEach(inject(function (xService) {
xService.getXData().then(function (data) {
xData = data;
});
}));
describe('definition', function () {
it('should be called', inject(function (xService) {
xService.getXData().then(function (data) {
xData = data;
});
expect(xData).toBeDefined();
}));
});
});