4

How can I unit test a function inside a directive's link? I tried something like this, but not worked:

directive:

app.directive("hello", function(){
  return {
    link: function(scope){
      scope.hello = function(){
        return "hello";
      };
    }
  };
});

unit test:

describe("Hello directive", function(){
  var compile, scope;

  beforeEach(inject(function($compile, $rootScope){
    scope = $rootScope.$new();
    compile = $compile;
  }));

  it("should return hello", function(){
    var element = compile("<hello></hello>")(scope);
    expect(element.scope.hello()).toBe("hello");
  });
});
5
  • Define "not worked". Why use element.scope.hello() and not simply scope.hello()? Also, element.scope is a function returning the scope of the element, as documented: docs.angularjs.org/api/ng/function/angular.element. So it should be element.scope().hello(). Commented May 23, 2014 at 10:11
  • The result with element.scope().hello() is the same: "TypeError: 'undefined' is not a function (evaluating 'element.scope().hello()')" Commented May 23, 2014 at 10:29
  • And with scope.hello(), too. Commented May 23, 2014 at 10:31
  • 3
    Your directive is not applied, because its default restrict is 'A'. So you would need <div hello></div> for this directive to be applied. Set the restrict field to 'E' if you want the directive to be applied using <hello></hello> Commented May 23, 2014 at 10:44
  • 2
    That's correct. One more command failed in the test: beforeEach(module("myApp")); Now it's working. If you write it down in the answer, I will accept it. Commented May 23, 2014 at 11:46

1 Answer 1

2

You are missing a call to module.

The directives restrict looks just fine (nowadays) as the default is 'EA' as per the angular source for $compileProvider.

Note: Said default was introduced in angular-1.3.0(commit: 11f5ae, PR: 8321), prior to that version it was simply 'A'. Which would have been an issue in your case, seeing as how your question was posted in May'14.

I setup a fiddle showcasing your implementation with two changes;

  • A call to module, so as to load your directive definition.
  • Bumped the angular version to 1.3.0.

jsFiddle


yes I'm late to the party, but your question remains one of the top unanswered questions in [angularjs]+[unit-testing]. figured I'd have a go at changing that.

Sign up to request clarification or add additional context in comments.

Comments

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.