Reputation: 1271
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
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;
module
, so as to load your directive definition.1.3.0
. 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