如何对指令链接中的函数进行单元测试?我尝试了这样的事情,但没有奏效:
指示:
app.directive("hello", function(){
return {
link: function(scope){
scope.hello = function(){
return "hello";
};
}
};
});
单元测试:
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");
});
});
最佳答案
您错过了对 module
的调用.
指令限制看起来很好(现在),因为默认是 'EA'
根据 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.
我设置了一个 fiddle 来展示你的实现,有两个变化;
module
,以便加载您的指令定义。 1.3.0
. jsFiddle
是的,我迟到了,但你的问题仍然是 [angularjs]+[unit-testing] 中最重要的未回答问题之一。我想我会尝试改变它。
关于AngularJS/Karma - 指令中的单元测试功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23826416/