How to test AngularJS custom provider

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

    I only needed to test that some settings were being set correctly on the provider, so I used Angular DI to configure the provider when I was initialising the module via module().

    I also had some issues with the provider not being found, after trying some of the above solutions, so that emphasised the need for an alternative approach.

    After that, I added further tests that used the settings to check they were reflecting the use of new setting value.

    describe("Service: My Service Provider", function () {
        var myService,
            DEFAULT_SETTING = 100,
            NEW_DEFAULT_SETTING = 500;
    
        beforeEach(function () {
    
            function configurationFn(myServiceProvider) {
                /* In this case, `myServiceProvider.defaultSetting` is an ES5 
                 * property with only a getter. I have functions to explicitly 
                 * set the property values.
                 */
                expect(myServiceProvider.defaultSetting).to.equal(DEFAULT_SETTING);
    
                myServiceProvider.setDefaultSetting(NEW_DEFAULT_SETTING);
    
                expect(myServiceProvider.defaultSetting).to.equal(NEW_DEFAULT_SETTING);
            }
    
            module("app", [
                "app.MyServiceProvider",
                configurationFn
            ]);
    
            function injectionFn(_myService) {
                myService = _myService;
            }
    
            inject(["app.MyService", injectionFn]);
        });
    
        describe("#getMyDefaultSetting", function () {
    
            it("should test the new setting", function () {
                var result = myService.getMyDefaultSetting();
    
                 expect(result).to.equal(NEW_DEFAULT_SETTING);
            });
    
        });
    
    });
    

提交回复
热议问题