angularjs - Mocking collaborators in Angular controller and service Jasmine tests -
i have been writing jasmine unit tests in angular. in first example i'm testing controller.
myapp.controller('myctrl', function($scope, config){ ... });
i have configuration service (config) keeps configuration database , injected controller. unit test, want mock out configuration service altogether, rather allowing execution pass through , using $httpbackend. examples found taught me $controller function can use this, in order instance of controller mocks injected in place of usual collaborator:
beforeeach(inject(function($controller, $rootscope){ var scope = $rootscope.$new(); var configmock = { theonlypropertymycontrollerneeds: 'value' }; ctrl = $controller('myctrl', { $scope:scope, config: configmock }); }));
but have other services use config service. unit test them, assumed there similar $service function use instantiate service whatever mocks want provide. there isn't. tried $injector.get, doesn't seem let me pass in mocks. after searching while, best come in order instantiate service in isolation (avoid instantiating collaborators) this:
beforeeach(function() { mockconfig = { thepropertymyserviceuses: 'value' }; module(function($provide) { $provide.value('config', mockconfig); }); inject(function($injector) { myservice = $injector.get('myservice'); }); });
is right way? seems overriding entire application's definition of config service, seems maybe overkill.
is way? why there no $service helper method?
for unit testing, common override service sake of testing. however, can use $provide override existing service instead of using inject, long load application before hand.
assuming created config
using like:
angular.moduel('...', [...]).factory('config', function (...) {...});
if so, try this:
... beforeeach(module("<name of app>")); beforeeach( module(function ($provide) { $provide.factory('config', function (...) {...}); }); ); ...
after that, when initialise controller, mocked config
.
Comments
Post a Comment