How to test AngularJS custom provider

前端 未结 6 908
無奈伤痛
無奈伤痛 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:25

    I had this same question and only found a working solution in this Google Group answer and it's referenced fiddle example.

    Testing your provider code would look something like this (following the code in the fiddle example and what worked for me):

    describe('Test app.config provider', function () {
    
        var theConfigProvider;
    
        beforeEach(function () {
            // Initialize the service provider 
            // by injecting it to a fake module's config block
            var fakeModule = angular.module('test.app.config', function () {});
            fakeModule.config( function (configProvider) {
                theConfigProvider = configProvider;
            });
            // Initialize test.app injector
            module('app.config', 'test.app.config');
    
            // Kickstart the injectors previously registered 
            // with calls to angular.mock.module
            inject(function () {});
        });
    
        describe('with custom configuration', function () {
            it('tests the providers internal function', function () {
                // check sanity
                expect(theConfigProvider).not.toBeUndefined();
                // configure the provider
                theConfigProvider.mode('local');
                // test an instance of the provider for 
                // the custom configuration changes
                expect(theConfigProvider.$get().mode).toBe('local');
            });
        });
    
    });
    

提交回复
热议问题