我很新的angularJS。试图测试与httpBackend角度服务,但不能让它的工作。我究竟做错了什么?试穿所以有类似问题的其他答案,但我得到的最接近于在下列(仍无法正常工作,外部数据是不确定的):
xApp.services.js
使用严格的;VAR的服务= angular.module('xApp.services',[]);services.factory('Xservice的',函数($ HTTP,$位置){ VAR urlPath = $ location.path()||的http://本地主机:8000'; VAR XDATA; VAR getXData =功能(){ VAR承诺= $ http.get(urlPath +'/ XDATA') 。然后(功能(RES){ XDATA = res.data; 返回XDATA; }); 返回的承诺; }; 返回{ getXData:getXData };});
xServiceSpec.js
描述('Xservice的',函数(){ beforeEach(模块('xApp.services')); 变量$ httpBackend; VAR XDATA; beforeEach(注入(函数($喷油器){ $ httpBackend = $ injector.get('$ httpBackend'); $ httpBackend.when(GET,/ XDATA')。反应( { _id:25, 名称:测试名 xarr: { _id:11, 名称:TestArrName 发布:2013年9月29日 } ] } ); $ httpBackend.when('POST','/newXArr').respond(\"ok); })); beforeEach(注(功能(Xservice的){ xService.getXData()。然后(功能(数据){ XDATA =数据; }); })); 描述(定义,函数(){ 它('应该叫'注入(功能(Xservice的){ xService.getXData()。然后(功能(数据){ XDATA =数据; }); 期待(XDATA).toBeDefined(); })); });});
解决方案
由于@EduardGamonal在他的评论中提到的,你需要调用 $ httpBackend.flush()
,但你应该把它的之后的你犯了一个HTTP请求,即在 xService.getXData()
;否则,就不会有优秀的HTTP请求来处理,因此$ httpBackend会给你没有挂起请求刷新的错误。
I am quite new to angularJS. Trying to test an angular service with httpBackend but can't get it working. What am I doing wrong? Tried other answers on SO having similar issues, but the closest I got to was the following (still not working, the xData is undefined):
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();
}));
});
});
解决方案
As @EduardGamonal mentioned in his comment, you need to call $httpBackend.flush()
, but you should call it after you made a http request, that is after xService.getXData()
; otherwise, there will be no outstanding http request to handle, so $httpBackend will give you the "No pending request to flush" error.