How to test AngularJS custom provider

前端 未结 6 896
無奈伤痛
無奈伤痛 2020-12-07 13:49

Does anyone have an example of how to unit test a provider?

For example:

config.js

an         


        
6条回答
  •  执笔经年
    2020-12-07 14:29

    @Stephane Catala's answer was particularly helpful, and I used his providerGetter to get exactly what I wanted. Being able to get the provider to do initialization and then the actual service to validate that things are working correctly with various settings was important. Example code:

        angular
            .module('test', [])
            .provider('info', info);
    
        function info() {
            var nfo = 'nothing';
            this.setInfo = function setInfo(s) { nfo = s; };
            this.$get = Info;
    
            function Info() {
                return { getInfo: function() {return nfo;} };
            }
        }
    

    The Jasmine test spec:

        describe("provider test", function() {
    
            var infoProvider, info;
    
            function providerGetter(moduleName, providerName) {
                var provider;
                module(moduleName, 
                             [providerName, function(Provider) { provider = Provider; }]);
                return function() { inject(); return provider; }; // inject calls the above
            }
    
            beforeEach(function() {
                infoProvider = providerGetter('test', 'infoProvider')();
            });
    
            it('should return nothing if not set', function() {
                inject(function(_info_) { info = _info_; });
                expect(info.getInfo()).toEqual('nothing');
            });
    
            it('should return the info that was set', function() {
                infoProvider.setInfo('something');
                inject(function(_info_) { info = _info_; });
                expect(info.getInfo()).toEqual('something');
            });
    
        });
    

提交回复
热议问题