Friday 15 July 2011

How can I mock a provider when testing a config function in AngularJS? -



How can I mock a provider when testing a config function in AngularJS? -

i have config function signature:

tmsnav = angular.module('tmsnav', ['tmsauthsvc', 'tmsconfig', 'ui.router']) tmsnav.config(function ($stateprovider, $urlrouterprovider, statesconfig) { // uses constant statesconfig configure $stateprovider , $urlrouterprovider });

here describe block:

describe('tmsnav.config() >', function () { it('configures states correctly', function () { module('tmsconfig', function ($provide) { $provide.constant('statesconfig', states1); $provide.factory('$state', function () { homecoming { state: function () { console.log('state()!!!'); } }; }); }); module('tmsnav'); inject(function ($state) { expect($state.get().length).tobe(4); }); }); });

the constant overwritten, $stateprovider isn't. i've tried using $provide.factory('$state', ...), $provide.constant('$stateprovider', ...), $provide.value('$state', ...), etc... nil has worked.

i need mock $stateprovider because 1 time it's configured retains configuration going next test. when run subsequent tests errors duplicate configuration values when shouldn't.

the reply lies in module() statements. trying overwrite $stateprovider on wrong module.

module('tmsconfig', function ($provide) { $provide.constant('statesconfig', states1); }); module('ui.router', function ($provide) { $provide.provider('$state', function () { this.state = function () { console.log('state()!!!'); }; this.$get = function () { homecoming { get: function () { homecoming []; } }; }; }); }); module('tmsnav');

this edit causes test pass if cut down length expectation zero. that's not test want anyway i'll write more robust mock spies , such provider issue resolved.

angularjs unit-testing karma-jasmine

No comments:

Post a Comment