How to test AngularJS custom provider

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

    here is a little helper that properly encapsulates fetching providers, hence securing isolation between individual tests:

      /**
       * @description request a provider by name.
       *   IMPORTANT NOTE: 
       *   1) this function must be called before any calls to 'inject',
       *   because it itself calls 'module'.
       *   2) the returned function must be called after any calls to 'module',
       *   because it itself calls 'inject'.
       * @param {string} moduleName
       * @param {string} providerName
       * @returns {function} that returns the requested provider by calling 'inject'
       * usage examples:
        it('fetches a Provider in a "module" step and an "inject" step', 
            function() {
          // 'module' step, no calls to 'inject' before this
          var getProvider = 
            providerGetter('module.containing.provider', 'RequestedProvider');
          // 'inject' step, no calls to 'module' after this
          var requestedProvider = getProvider();
          // done!
          expect(requestedProvider.$get).toBeDefined();
        });
       * 
        it('also fetches a Provider in a single step', function() {
          var requestedProvider = 
            providerGetter('module.containing.provider', 'RequestedProvider')();
    
          expect(requestedProvider.$get).toBeDefined();
        });
       */
      function providerGetter(moduleName, providerName) {
        var provider;
        module(moduleName, 
               [providerName, function(Provider) { provider = Provider; }]);
        return function() { inject(); return provider; }; // inject calls the above
      }
    
    • the process of fetching the provider is fully encapsulated: no need for closure variables that reduce isolation between tests.
    • the process can be split in two steps, a 'module' step and an 'inject' step, which can be respectively grouped with other calls to 'module' and 'inject' within a unit test.
    • if splitting is not required, retrieving a provider can simply be done in a single command!

提交回复
热议问题