我如何测试AngularJS提供程序?

时间:2013-03-13 16:58:19

标签: unit-testing angularjs jasmine

我需要测试我自己的角度提供程序,我需要在配置和运行阶段测试它以检查配置方法是否有效以及实例化的提供程序确实配置​​了正确的参数。

当我向提供者请求依赖注入时,它找不到APIResourceFactoryProvider,只找到APIResourceFactory,而且我还没有在目前为止看到的存储库中找到任何这样的例子。

3 个答案:

答案 0 :(得分:20)

它实际上比最初似乎在AngularJS中测试提供程序要简单得多:

describe('Testing a provider', function() {
  var provider;

  beforeEach(module('plunker', function( myServiceProvider ) {
      provider = myServiceProvider;
  }));

  it('should return true on method call', inject(function () {
    expect( provider.method() ).toBeTruthy();
  }));
});

```

证据在Plunker中:http://plnkr.co/edit/UkltiSG8sW7ICb9YBZSH

答案 1 :(得分:1)

如果您希望获得提供商的缩小版本,事情会变得稍微复杂一些。

以下是提供商代码:

angular
    .module('core.services')
    .provider('storageService', [function () {
        function isLocalStorageEnabled(window) {
            return true;
        }

        this.$get = ['$window', 'chromeStorageService', 'html5StorageService',
            function($window, chromeStorageService, html5StorageService) {
            return isLocalStorageEnabled($window) ? html5StorageService : chromeStorageService;
        }];
    }]);

测试用例:

describe('Storage.Provider', function() {
    var chrome = {engine: 'chrome'};
    var html5 = {engine: 'html5'};
    var storageService, provider;

    beforeEach(module('core.services'));
    beforeEach(function () {
        module(function (storageServiceProvider) {
            provider = storageServiceProvider;
        });
    });
    beforeEach(angular.mock.module(function($provide) {
        $provide.value('html5StorageService', html5);
        $provide.value('chromeStorageService', chrome);
    }));

    // the trick is here
    beforeEach(inject(function($injector) {
        storageService = $injector.invoke(provider.$get);
    }));

    it('should return Html5 storage service being run in a usual browser', function () {
        expect(storageService).toBe(html5);
    });
});

在这种情况下,$ get是一个数组,您不能将其称为通常的函数,将依赖项作为参数。解决方案是使用 $ injector.invoke()

奇怪的是,大多数教程和样本都错过了这个细节。

答案 2 :(得分:0)

这里有一个小帮手,可以正确封装提取提供程序,从而确保各个测试之间的隔离:

  /**
   * @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
  }
  • 获取提供程序的过程是完全封装的:不需要关闭测试之间隔离的闭包变量。
  • 该过程可以分为两个步骤,一个'模块'步骤和注入'步骤,可以与其他对“模块”的调用进行适当的分组。和'注入'在单元测试中。
  • 如果不需要拆分,只需在一个命令中检索提供程序即可!