Mocking AngularJS module dependencies in Jasmine unit tests Mocking AngularJS module dependencies in Jasmine unit tests angularjs angularjs

Mocking AngularJS module dependencies in Jasmine unit tests


If you want to mock a module that declare one or more services I have used this code:

beforeEach(function(){    module('moduleToMock');    module(function ($provide) {        $provide.value('yourService', serviceMock);    });});

This is useful if the service you want to mock is also a service that you want to unit test (in another jasmine describe). The solution proposed by fscof is fine but you cannot create a unit test for the angular-table module.


Here's what I figured out:

I wasn't loading any 'angular-table' modules in my karma.conf.js file, hence the error. This was intentional at first as I wanted to test the 'events' module without the actual table module.

I was able to easily mock the 'angular-table' module by creating a new file in my test folder called 'mocks/angular-table.js' and added the following code:

/mocks/angular-table.js

'use-strict';angular.module('angular-table', []);

I added this file to my karma.conf.js file, along with the real 'events' module I wanted to test:

karma.conf.js

...files = [    JASMINE,    JASMINE_ADAPTER,    'scripts/libs/angular.js',    'scripts/libs/angular-mocks.js',    'scripts/events.js', // this is the real module.    'scripts/mocks/*.js', //loads all custom mocks.    'scripts/specs/*.spec.js' // loads my spec file.] ...

Finally in my spec file, I was able to add both modules by calling them separately in a beforeEach block:

specs/events.spec.js

beforeEach(function(){    module('angular-table');    module('events');});

I got the idea to structure my files in this way from this post


I recently released ngImprovedTesting that should make mock testing in AngularJS way easier.

In your case just use the following in your Jasmine test:

beforeEach(ModuleBuilder.forModule('events').serviceWithMocks('eventsCtrl').build());

For more information about ngImprovedTesting check out its introductory blog post: http://blog.jdriven.com/2014/07/ng-improved-testing-mock-testing-for-angularjs-made-easy/