Tiger
Tiger

Reputation: 157

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.

Upvotes: 6

Views: 5213

Answers (1)

Florian F
Florian F

Reputation: 8875

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);

Upvotes: 3

Related Questions