简体   繁体   中英

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

I have a config function with this signature:

tmsNav = angular.module('tmsNav', ['tmsAuthSvc', 'tmsConfig', 'ui.router'])
tmsNav.config(function ($stateProvider, $urlRouterProvider, statesConfig) {
    // uses the constant statesConfig to configure $stateProvider and $urlRouterProvider
});

Here is my describe block:

describe('tmsNav.config() >', function () {
    it('configures states correctly', function () {
        module('tmsConfig', function ($provide) {
            $provide.constant('statesConfig', states1);
            $provide.factory('$state', function () {
                return {
                    state: function () {
                        console.log('state()!!!');
                    }
                };
            });
        });
        module('tmsNav');
        inject(function ($state) {
            expect($state.get().length).toBe(4);
        });
    });
});

The constant is successfully overwritten, but $stateProvider isn't. I've tried using $provide.factory('$state', ...) , $provide.constant('$stateProvider', ...) , $provide.value('$state', ...) , etc... Nothing has worked.

I need to mock $stateProvider because once it's configured it retains that configuration going into the next test. So when I run subsequent tests I get errors about duplicate configuration values when I shouldn't.

The answer lies in the module() statements. I was trying to overwrite $stateProvider on the 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 () {
            return {
                get: function () {
                    return [];
                }
            };
        };
    });
});
module('tmsNav');

This edit causes the test to pass if I reduce the length expectation to zero. That's not really the test I want anyway so I'll write a more robust mock with spies and such now that the provider issue is resolved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM