vendredi 23 janvier 2015

Angular/Jasmine: adding .error to callback seems to break unit tests

I encountered an error that occurs only when I have the .error part of my http callback defined. Here is the relevant part of the controller I'm testing:



vm.dirtyTestGraph = function() {
vm.graphTitle = 'Deposit Amount';

$timeout(function(){
ChartService.get( {index: 'transaction', 'type': 'deposit', period: 'week'} )
.success(function(res){
vm.graphLoading = false;
vm.chartData = res.data;
}).error(function(err){ //<- HERE
console.log(err);
});
}, 2000);


And the unit test to cover it:



describe('Unit: HomeCtrl', function() {
var ctrl, scope, $timeout, $httpBackend, Chart, ChartService,uuid4;

beforeEach(module('dashboardApp'));
beforeEach(inject(function($controller, $rootScope,_$httpBackend_, _Chart_,
_$timeout_,_ChartService_,_uuid4_) {
scope = $rootScope.$new();
$timeout = _$timeout_;
Chart = _Chart_;
ChartService = _ChartService_;
$httpBackend = _$httpBackend_;
uuid4 = _uuid4_;
spyOn(uuid4,'generate').and.returnValue("1");


spyOn(ChartService, 'get').and.callFake(function() {
return {
success: function(callback) { callback( {error:0, data:[{count:'101', time:1416960000000}]} ); },
error: function(err) { err( {error:1 }); }
};
});

ctrl = $controller('HomeCtrl as vm', {
$scope: scope,
Chart: _Chart_,
ChartService:_ChartService_
});
}));
it('test graph loading async', function() {
scope.vm.dirtyTestGraph();
$timeout.flush();
scope.$digest();
expect(scope.vm.chartData).toEqual([{count:'101', time:1416960000000}]);
expect(scope.vm.graphLoading).toBe(false);
});
});


my unit test fails with:



TypeError: 'undefined' is not an object (near '...}).error(function(err)...')


However if I uncomment the .error() part of my ChartService.get()...


The test passes, why? How can I change my test so I can leave both the .success and .error in my controller?


Aucun commentaire:

Enregistrer un commentaire