How to mock a module in angular

后端 未结 2 1842
说谎
说谎 2021-01-18 05:18

So I\'ve read many posts but no suggestions as worked so far.

I am wanting to mock a module - say angular-foo. The original file is loaded along with everything else

相关标签:
2条回答
  • 2021-01-18 05:45

    To mock factory, service and value services, angular.mock.module object argument can be used

    beforeEach(module('app', 'angular-foo', {
      fooFactoryService: ...,
      fooValueService: ...
    }));
    

    To mock the services that are available for injection during config phase (constant and provider), config function should be used

    beforeEach(module('app', 'angular-foo', ($provide) => {
      $provide.constant('fooConstantService', ...),
      $provide.provider('fooProviderService', ...),
    }));
    

    The last module in the row overrides the services from the other ones. The services can be mocked partially (with $provide.decorator) or entirely.

    If angular-foo module isn't loaded at all but other modules make use of it, it can be fully redefined in specs with its mocked version with

    angular.module('angular-foo', [])...
    beforeEach(module('app', 'angular-foo'));
    
    0 讨论(0)
  • 2021-01-18 06:00

    What did the trick for me was putting the provider before the module declaration:

      beforeEach(module(function($provide) {
        $provide.provider('myProvider', function() {
          return {
            myProviderFunction: function() {},
    
            $get: function () {
              return {
                myProviderFunction: function() {}
              };
            }
          };
        });
      }));
    
      beforeEach(module('myApp'));
    
    0 讨论(0)
提交回复
热议问题