Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing AngularJS directives

How can I unit test my directive?

What I have is

angular.module('MyModule').
    directive('range', function() {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                bindLow: '=',
                bindHigh: '=',
                min: '@',
                max: '@'
            },
        template: '<div><select ng-options="n for n in [min, max] | range" ng-model="bindLow"></select><select ng-options="n for n in [min, max] | range" ng-model="bindHigh"></select></div>'
    };
})

In my unit test I want to start with a very simple test

describe('Range control', function () {
    var elm, scope;

    beforeEach(inject(function(_$compile_, _$rootScope) {
        elm = angular.element('<range min="1" max="20" bind-low="low" bind-high="high"></range>');

        var scope = _$rootScope_;
        scope.low = 1;
        scope.high = 20;
        _$compile_(elm)(scope);
        scope.$digest();
    }));

    it('should render two select elements', function() {
        var selects = elm.find('select');

        expect(selects.length).toBe(2);
    });
});

This doesn't work though as the directive is registered on the app module and I don't want to include the module as that will make all of my config and runcode run. That would defeat the purpose of testing the directive as a separate unit.

Am I supposed to put all my directives in a separate module and load just that? Or is there any other clever way of solving this?

like image 666
Oscar Avatar asked Mar 25 '13 19:03

Oscar


2 Answers

EDIT: I see the question has changed since my last answer.

You need to put your directive in an independant module.

For example:

angular.module('MyModule.directives');

To test only that module you may load that module explicitly in the test like this:

beforeEach(module('MyModule.directives'));

This will load that module and all its dependancies.

Remember to state the directive module as a dependancy in your MyModule definition in your app:

angular.module('MyModule', ['MyModule.directives', ...]);
like image 101
Kenneth Lynne Avatar answered Oct 04 '22 02:10

Kenneth Lynne


You should declare all your directives in 'youapp.directives' module and include that module in your directive tests.

In your app.js

angular.module('myApp', ['myApp.controllers', 'myApp.directives', 'myApp.services', 'myApp.filters']).config(...)

In your directives.js

angular.module('myApp.directives', []) .directive(.....)

Finally your directivesSpec.js

describe('directives specs', function() {
    beforeEach(module('myApp.directives'));

    describe('range', function() {
    ...
    });
});
like image 42
hotienvu Avatar answered Oct 04 '22 02:10

hotienvu