coderdark
coderdark

Reputation: 1501

Multiple angular modules with same dependencies for karma testing

I have a question. I have multiple angular modules that have the same dependency need. Currently the code below works well for the application to run but not for testing...see below

angular.module('app',['d1','d2']) angular.module('app.home', []); angular.module('app.about',[]);

I am also doing karma testing so when I pass the 'app.about' module and karma is asking for the 'd1' dependency. I then added 'app' module and it works but I will have to add 'd2' to my 'app.about' specs even though 'd2' has nothing to do with 'app.about'.

I then proceeded to do the below fixes: angular.module('app',['d1','d2']) angular.module('app.home', ['d1']); angular.module('app.about',['d1']);

It feels that is repetitive. So my question is...is this how angular modules work? What if later I use 'd1' and 'd2' in all my modules? Would this not make my modules repetitive? Again, I need the code below because of karma testing.

angular.module('app',['d1','d2']) angular.module('app.home', ['d1','d2']); angular.module('app.about',['d1','d2']);

Thanks for your help. P.S. I looked at johnpapa's guide but I did not seem to be clear on this.

Upvotes: 1

Views: 665

Answers (2)

coderdark
coderdark

Reputation: 1501

I found the fix...i had a login service (in a 'login' module) that was injected in a controller (in the 'about' module) and the run block (in the 'app' module). I had to move the login service to the 'core' module of the application and it worked like a charm. The 'core' module had all 3rd party dependencies and core modules used through out the app. The 'app' module had the 'login', 'about' and 'core' modules. No need to mock up other services. :)

Upvotes: 0

Amy Blankenship
Amy Blankenship

Reputation: 6961

You only need to supply mock dependencies if those dependencies will affect the outcome of the tests. Often they won't. However, you can "remap" any dependency by simply registering your mock over the top of the actual implementation.

For example:

(function() {
    'use strict';
    var serviceId = 'apiService';
    angular.module('app').factory(serviceId,
        ['$q', apiService]);

    function apiService($q) {
        var service = {
            sendData: mockFunction,
            saveUserState: mockFunction
        }

        return service;


        function mockFunction(){return $q.when({})}

    }

})();

The down side is this mocked version will be used everywhere, but that is often what you want.

Note that if app.home and app.about don't contain implicit dependencies on things in d2, you should be able to avoid bootstrapping d2 by just initializing the module under test:

beforeEach(module('app.home'));

Upvotes: 1

Related Questions