Jasmine AngularJS : Mock a $scope property? -
i've got angularjs controller :
app.controller('myctrl', function($scope, myfactory){ $scope.types = myfactory.gettypes(); $scope.model= {}; $scope.model.type = $scope.types[0].type; }); });
everything works fine.
but want test controller in jasmine. mock myfactory
, init myctrl
that:
describe('controllers: myctrl', function () { var myctrl, mockedfactory, scope; beforeeach(module('app.factories', function ($provide) { mockedfactory = { gettypes: function(){} }; spyon(mockedfactory, 'gettypes'); $provide.value('myfactory', mockedfactory); })); beforeeach(module('app')); beforeeach(inject(function ($rootscope, $controller) { scope = $rootscope.$new(); myctrl= $controller('myctrl', { $scope: scope }); })); it('should call accordtypefactory.getavailabletypes()', function () { scope.types; expect(mockedfactory.gettypes).tohavebeencalled(); });
but i've got logic bug : cannot read property 0 of undefined
i understand bug; because mock factory controller property $scope.model.type
it's undefined because use result of factory through $scope.types
.
my question simple: how can make work test ?
thx guys
beforeeach(module('app.factories', function ($provide) { mockedfactory = { gettypes: function(){ return [{}]; } }; spyon(mockedfactory, 'gettypes').andcallthrough(); $provide.value('myfactory', mockedfactory); }));
if understood correctly problem mock not return array while controller expects there @ least 1 element in it. set mock return array element , use andcallthrough()
on spy have call mock.
if possible factory can return empty arrays while application running, you'd want check array contains @ least 1 element before trying access types[0]
Comments
Post a Comment