53

有没有人有一个如何对提供者进行单元测试的例子?

例如:

配置.js

angular.module('app.config', [])
  .provider('config', function () {
    var config = {
          mode: 'distributed',
          api:  'path/to/api'
        };

    this.mode = function (type) {
      if (type) {
        config.isDistributedInstance = type === config.mode;
        config.isLocalInstance = !config.isDistributedInstance;
        config.mode = type;
        return this;
      } else {
        return config.mode;
      }
    };

    this.$get = function () {
      return config;
    };
  }]);

应用程序.js

angular.module('app', ['app.config'])
  .config(['configProvider', function (configProvider) {
    configProvider.mode('local');
  }]);

app.js正在测试中使用,我看到已经配置configProvider,我可以将其作为服务进行测试。但是如何测试配置能力呢?还是根本不需要?

4

6 回答 6

64

我有同样的问题,只在这个Google Group 答案中找到了一个可行的解决方案,它被引用了fiddle example

测试您的提供程序代码看起来像这样(按照小提琴示例中的代码以及对我有用的代码):

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');
        });
    });

});
于 2013-06-29T09:06:49.047 回答
46

我一直在使用@Mark Gemmill 的解决方案,它运行良好,但后来偶然发现了这个稍微不那么冗长的解决方案,它消除了对假模块的需求。

https://stackoverflow.com/a/15828369/1798234

所以,

var provider;

beforeEach(module('app.config', function(theConfigProvider) {
    provider = theConfigProvider;
}))

it('tests the providers internal function', inject(function() {
    provider.mode('local')
    expect(provider.$get().mode).toBe('local');
}));


如果您的提供者 $get 方法具有依赖项,您可以手动传递它们,

var provider;

beforeEach(module('app.config', function(theConfigProvider) {
    provider = theConfigProvider;
}))

it('tests the providers internal function', inject(function(dependency1, dependency2) {
    provider.mode('local')
    expect(provider.$get(dependency1, dependency2).mode).toBe('local');
}));


或者使用 $injector 创建一个新实例,

var provider;

beforeEach(module('app.config', function(theConfigProvider) {
    provider = theConfigProvider;
}))

it('tests the providers internal function', inject(function($injector) {
    provider.mode('local')
    var service = $injector.invoke(provider);
    expect(service.mode).toBe('local');
}));


以上两种方法还允许您为块it中的每个单独语句重新配置提供程序describe。但是如果你只需要为多个测试配置一次提供程序,你可以这样做,

var service;

beforeEach(module('app.config', function(theConfigProvider) {
    var provider = theConfigProvider;
    provider.mode('local');
}))

beforeEach(inject(function(theConfig){
    service = theConfig;
}));

it('tests the providers internal function', function() {
    expect(service.mode).toBe('local');
});

it('tests something else on service', function() {
    ...
});
于 2014-10-31T11:54:27.820 回答
4

@Stephane Catala 的回答特别有帮助,我使用他的 providerGetter 来得到我想要的。能够让提供者进行初始化,然后通过实际服务来验证各种设置是否正常工作,这一点很重要。示例代码:

    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;} };
        }
    }

Jasmine 测试规范:

    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');
        });

    });
于 2015-07-19T03:43:50.713 回答
2

这是一个小助手,它正确封装了获取提供程序,从而确保各个测试之间的隔离:

  /**
   * @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
  }
  • 获取提供者的过程是完全封装的:不需要减少测试之间隔离的闭包变量。
  • 该过程可以分为两个步骤,一个“模块”步骤和一个“注入”步骤,它们可以分别与单元测试中对“模块”和“注入”的其他调用进行分组。
  • 如果不需要拆分,则可以在单个命令中简单地检索提供者!
于 2015-04-22T17:52:53.527 回答
1

我个人使用这种技术来模拟来自外部库的提供程序,您可以将其放入所有测试的帮助文件中。当然,它也可以用于自定义提供程序,就像这个问题一样。这个想法是在应用程序调用它之前在他的模块中重新定义提供程序

describe('app', function() {
  beforeEach(module('app.config', function($provide) {
    $provide.provider('config', function() {
      var mode = jasmine.createSpy('config.mode');

      this.mode = mode;

      this.$get = function() {
        return {
          mode: mode
        };
      };
    });
  }));

  beforeEach(module('app'));

  describe('.config', function() {
    it('should call config.mode', inject(function(config) {
      expect(config.mode).toHaveBeenCalled();
    }));
  });
});
于 2016-04-21T03:38:13.423 回答
1

我只需要测试提供程序上的某些设置是否正确设置,因此我在通过module().

在尝试了上述一些解决方案之后,我还遇到了一些关于未找到提供者的问题,因此强调了需要一种替代方法。

之后,我添加了进一步的测试,使用这些设置来检查它们是否反映了新设置值的使用。

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);
        });

    });

});
于 2016-08-12T16:35:10.563 回答