如何重新创建AngularJS服务以进行测试?

时间:2015-12-22 12:13:26

标签: angularjs unit-testing angularjs-service

我想测试myService初始化,这可能会有所不同取决于条件:

service('myService', function(internalService){
   if(internalService.param){ init1(); }
   else { init2(); }

   //...
});

我可以模仿internalService,但如何重新创建myService

1 个答案:

答案 0 :(得分:1)

在配置阶段之后,注入器(inject(...))将实例化服务。要测试初始化​​,您需要做的就是在每个测试中设置不同。也就是说,不是在beforeEach块中实例化您的服务,而是在测试中进行。

例如,您可以通过模拟init1internalService

来测试使用param: true实例化的副作用
describe('Unit: myService', function() {
  it('should perform init1 if internalService.param', function() {
    var mockInternalService = {
      param: true,
    };

    // config phase (mocking)
    module('app', function($provide) {
      $provide.constant('internalService', mockInternalService);
    });

    inject(function($injector) {
      myService = $injector.get('myService');

      // assert side effects from init1();
    });
  });
});

要测试init2的副作用,只需模仿internalServiceparam: false

  it('should perform init2 if !internalService.param', function() {
    var mockInternalService = {
      param: false,
    };

    // config phase (mocking)
    module('app', function($provide) {
      $provide.constant('internalService', mockInternalService);
    });

    inject(function($injector) {
      myService = $injector.get('myService');

      // assert side effects from init2();
    });
  });

编辑:当然,如果您想为每个配置进行多个测试,您可以创建两个describebeforeEach。{/ p>

  describe('Unit: myService', function() {
    var myService;

    describe('When instantiated with `init1`', function() {
      beforeEach(config(true));
      beforeEach(inject(injections));

      it('should do X');
    });

    describe('When instantiated with `init2`', function() {
      beforeEach(config(false));
      beforeEach(inject(injections));

      it('should do Y');
    });

    function config(param) {
       return function() { 
         var mockInternalService = {
           param: param,
         };

         // config phase (mocking)
         module('app', function($provide) {
           $provide.constant('internalService', mockInternalService);
         });
      };
    }

    function injections($injector) {
      myService = $injector.get('myService');
    }
  });