programing

AngularJS 사용자 지정 공급자를 테스트하는 방법

kingscode 2021. 1. 18. 08:11
반응형

AngularJS 사용자 지정 공급자를 테스트하는 방법


누구든지 공급자를 단위 테스트하는 방법에 대한 예가 있습니까?

예를 들면 :

config.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;
    };
  }]);

app.js

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

app.js테스트에서 사용 중이며 이미 구성 configProvider되어 있으며 서비스로 테스트 할 수 있습니다. 그러나 구성 기능을 어떻게 테스트 할 수 있습니까? 아니면 전혀 필요하지 않습니까?


나는이 같은 질문이 있었고이 Google 그룹 답변 에서만 작동하는 해결책을 찾았으며 참조 된 바이올린 예제 입니다.

공급자 코드를 테스트하는 것은 다음과 같을 것입니다 ( fiddle 예제 의 코드 와 저에게 도움이 된 것).

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

});

나는 @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() {
    ...
});

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

    });

다음은 가져 오는 공급자를 적절하게 캡슐화하여 개별 테스트 간의 격리를 보호하는 작은 도우미입니다.

  /**
   * @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!

Personally I use this technique to mock providers coming from external libraries, which you could put in a helper file for all your tests. It can also work for a custom provider as in this question of course. The idea is to redefine the provider in his module before it is called by the app

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

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

    });

});

ReferenceURL : https://stackoverflow.com/questions/14771810/how-to-test-angularjs-custom-provider

반응형