Kamil Lelonek
Kamil Lelonek

Reputation: 14754

How to mock Angular modules before injecting?

I have the following dependencies in my application:

angular.module 'MyApplication.NetworkingModule', ['ngResource']
       .value  'NetworkingValues'

angular.module  'MyApplication.MyModule', []
       .factory 'MySpecificResource', ['NetworkingValues',   ...]
       .factory 'MyService',          ['MySpecificResource', ...]

So MySpecificResource depends on NetworkingValues.

The thing is I'd like to mock some of these values before using them in resources in tests.

Doing this:

  beforeEach module 'MyApplication.NetworkingModule'
  beforeEach module 'MyApplication.MyModule'

causes that factory is invoked immediately and I don't have a chance to replace some of NetworkingValues.

beforeEach inject (@MyService, @NetworkingValues) ->

MyService depends on MySpecificResource, which depends on NetworkingValues that I want to stub before tests.

What are the correct way to do that?

Upvotes: 0

Views: 104

Answers (2)

Kamil Lelonek
Kamil Lelonek

Reputation: 14754

So my final solution was to provide constant and inject it together with module function:

beforeEach module "MyApplication.NetworkingModule", ($provide) ->
  $provide.constant 'NetworkingValues', endpointGet: 'my-endpoint/:id'

Upvotes: 0

Scott
Scott

Reputation: 1690

Have you tried something along these lines?

 var mockedValues;
 beforeEach(module(function($provide) {
        $provide.value('NetworkingValues',mockedValues);
 }));

 beforeEach(inject(function(_NetworkingValues_) {

    mockedValues = {....};

 }));

The $provide will supply your mockedValues instead of the actual NetworkingValues.

Upvotes: 1

Related Questions