mardi 24 novembre 2015

Mocking Module Dependencies in Karma/Jasmine for AngularJS

I'm trying to compose some unit tests in Karma/Jasmine for a particular module in my project, destination-filters.

Module Decleration:

angular.module('destination-filter', ['ngSanitize']);

My tests fail unless I remove ngSanitize as a dependency. To my understanding that is because when the module is instantiated it will try and pull in that dependency but because in my spec.js file I haven't declared that module it is failing.

Spec File:

describe('Destination Filter Controller', function () {

// Set the variables
var $controller;
var mockNgSanitize;

beforeEach(module('destination-filter'));

beforeEach(function() {
    module(function($provide) {
        $provide.value('ngSanitize', mockNgSanitize);
    });
});

beforeEach(inject(function (_$controller_) {
    $controller = _$controller_('DestinationFilterController');
}));

it('should expect the controller to not be null', function() {
    // Check the controller is set
    expect($controller).not.toBeNull();
});

});

Previously, when mocking out services or functions, the $provide method has proven very useful but I'm not sure my use of it is correct here. I'm assuming $provide used in this way can't mock entire modules but rather services?

To clarify, if I remove the ...['ngSantize'])... from my module deceleration the tests instantiate correctly. The error I am receiving with it left in is Error: [$injector:modulerr] destination-filter

Aucun commentaire:

Enregistrer un commentaire