Csati
Csati

Reputation: 1271

AngularJS/Karma - unit test function in directive

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

Upvotes: 4

Views: 3654

Answers (1)

user1364910
user1364910

Reputation:

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.

Upvotes: 2

Related Questions