Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a module in angular

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.

angular.module('app', ['angular-foo'...

I would like to mock this module in my karma/mocha tests. I've tried suggestions such as calling it like this but it's a no go.

beforeEach(module('app'));

beforeEach(module('angular-foo'))

How can I completely prevent the original angular-foo from running (yet it must load as part of the rest of the code)?

like image 276
cyberwombat Avatar asked May 07 '16 23:05

cyberwombat


2 Answers

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'));
like image 114
Estus Flask Avatar answered Sep 30 '22 21:09

Estus Flask


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'));
like image 39
Kiko Castro Avatar answered Sep 30 '22 20:09

Kiko Castro