Sunday 7 June 2015

Inject Module Dependancies into Unit Tests

When setting up unit tests for a module you need to make sure that your test harness is aware of any dependancies that module has. It doesn't stop there though; you also need to make sure that you include the dependancies of your dependancies. And so it goes on. Thankfully all dependancies are injected in the same way.

Example Code

Application declarations

angular.module('anotherApp', ['ngSanitize']);

angular.module('myApp', ['anotherApp']);

Test

describe('my application', function(){ 
    beforeEach(function(){ 
        module('ngSanitize'); 
        module('anotherApp'); 
        module('myApp'); 
    }); 

    //test code here
});

Dependancy Injecting

I've written about setting up Jasmine unit tests, which this post builds upon.

I always put everything to setup tests within beforeEach functions as it makes sure that everything is fresh and clean for each new test, which in turn gives me greater confidence in the results of the test. Every AngularJs module that requires injection needs to be called using module, which comes from angular-mocks. You can download this from npm or bower using one of the following commands from the root of your project:

npm install angular-mocks

bower install angular-mocks


Mocks has a function named module that takes a string parameter of the name of the AngularJs module that is required for testing. These need to be ordered correctly so that any dependancies a module requires has already been referenced. In the example above I want to test the module myApp, which has a dependancy upon the module anotherApp, which in turn has a dependancy upon ngSanitize.

As ngSantize has no dependancies it is referenced first. Out of anotherApp and myApp, the only one to have all it dependancies already referenced is anotherApp, so that one is added next. There remains only myApp, so it is referenced now. The rule is to list all modules that have no dependancies, then iteratively add all modules that have dependancies only upon those already referenced.

File Referencing

When modules are injected into tests in this way the test harness needs to have access to the source code files for them. Make sure that there are local copies of these files, and that they have been referenced in whichever manner the test harness requires in the correct order. For grunt-contrib-jasmine any dependancies should be referenced in the gruntfile.js configuration under options.vendor. For Visual Studio plugin, Chutzpah, dependancies are referenced using:

/// <reference path="path/to/dependancy" />

When using Jasmine in the browser dependancies are referenced in the standard HTML way, by including script tags.

No comments:

Post a Comment