6

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.

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

I've tried that as well as calling scope.$digest() directly, but without any results - I think because the directive doesn't actually use the scope.
Thank you, it works now! However, it's strange that it's working fine outside of the test both as element and attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.