Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing angularjs directive with dependencies

I'm new to AngularJs and having problem trying to test a directive with dependency (although the directive itself works as expected). I was unable to find any answers here or on the other resources.

Here is my code:

Directive:

angular.module('MyApp')
  .directive('appVersion', ['config', function (config) {
    return function (scope, elm) {
      elm.text(config.version);
    };
  }]);

Service (value):

angular.module('MyApp')
  .value('config', {
    version: '0.1'
  });

Test:

describe('Directive: AppVersion', function () {
    beforeEach(module('MyApp'));

    var element;

    it('should have element text set to config value', inject(function ($rootScope, $compile, config) {
        var scope = $rootScope;
        element = $compile('<app-version></app-version>')(scope);
        expect(element.text()).toBe(config.version);
    }));
});

My test is failing with message:

Error: Expected '' to be '0.1'.

meaning that config value got injected properly, but $complile was not using it. I would really appreciate any help on this. Thanks.

like image 512
Tiger Avatar asked Jul 11 '13 13:07

Tiger


People also ask

Can you conduct automated testing on Angular?

The Angular framework is a mature and comprehensive solution for enterprise-ready applications based on web technologies. At Angular's core lies the ability to test all application parts in an automated way.

Is AngularJS code unit testable?

AngularJS is written with testability in mind, but it still requires that you do the right thing. We tried to make the right thing easy, but if you ignore these guidelines you may end up with an untestable application.


1 Answers

You didn't specify the restrict attribute of the directive. When you don't specify it, that means angular looks for app-version declared as an attribute, not an element.

So you can either add the restrict attribute to the directive or change your template :

element = $compile('<div app-version></div>')(scope);
like image 71
Florian F Avatar answered Oct 20 '22 14:10

Florian F