我有一个调用资源然后操纵响应的指令。 我的单元测试总是给我"意想不到的请求GET"。我已经尝试过一些方法来模拟这些资源,但没有成功。如果有人知道该怎么做,请提前多多谢谢!
;(function(app){
'use strict';
app.directive('reportBalance', ['feelingsResource', function(feelingsResource){
function reportBalanceDirective(scope){
buildTotalObject(scope);
getFeelingsTotals(scope);
}
function buildTotalObject(scope){
scope.total = {
'sad' : 0,
'happy' : 0,
getFeelingsTotal : function(){
return this.sad + this.happy;
},
getPercentage: function(feeling) {
if(!this.getFeelingsTotal())
return '0%';
return (this[feeling] / this.getFeelingsTotal() * 100) + '%';
}
};
}
function getFeelingsTotals(scope){
feelingsResource.totals({}, function(response){
onGetFeelingsTotalSuccess(scope, response);
});
}
function onGetFeelingsTotalSuccess(scope, response){
scope.total.sad = Math.abs(response.totals.sad);
scope.total.happy = Math.abs(response.totals.happy);
}
return {
restrict: 'E',
scope: {},
templateUrl: 'app/commons/directives/reports/balance/report-balance-template.html',
link: reportBalanceDirective
};
}]);
})(app);
这是规范:
describe("Report Balance Directive:", function() {
var scope, element;
beforeEach(function(){
module('app');
module('templates');
});
beforeEach(inject(function($rootScope, $compile) {
scope = $rootScope.$new();
element = angular.element('<report-balance></report-balance>');
$compile(element)(scope);
scope.$digest();
}));
it('should contains a "totals" in its scope', function(){
expect(scope.totals).toBeDefined();
});
});
错误:
Error: Unexpected request: GET http://localhost:3000/feelings/totals
答案 0 :(得分:0)
嗯,您只需要使用mock $httpBackend,就像涉及$ http请求的任何其他单元测试一样:
$httpBackend.whenGET('/feelings/totals').respond(someData);
或者,因为您委托服务进行$ http查询,所以模拟服务本身:
spyOn(feelingsResource, 'totals').andCallFake(function(config, callback) {
callback(someData);
});