[英]How to mock a resource in a directive unit testing
I have a directive that calls a resource and then manipulate the response. 我有一个指令,该指令调用资源,然后操纵响应。 My unit test always give me "Unexpected request GET".
我的单元测试总是给我“意外的请求GET”。 I have tried some ways to mock this resources, but without success.
我尝试了一些方法来模拟此资源,但是没有成功。 If someone knows how to do that, thanks very much in advance!
如果有人知道该怎么做,请非常感谢!
;(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);
And here is the specification: 这是规范:
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: 错误:
Error: Unexpected request: GET http://localhost:3000/feelings/totals
Well, you just need to use the mock $httpBackend , as for any other unit test involving $http requests: 好吧,您只需要使用模拟$ httpBackend ,就可以使用任何其他涉及$ http请求的单元测试:
$httpBackend.whenGET('/feelings/totals').respond(someData);
Or, since you delegate to a service to make that $http query, to mock the service itself: 或者,由于您委托给服务进行该$ http查询,因此可以模拟服务本身:
spyOn(feelingsResource, 'totals').andCallFake(function(config, callback) {
callback(someData);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.