【发布时间】:2014-07-12 15:32:09
【问题描述】:
如何对指令链接中的函数进行单元测试?我尝试过这样的事情,但没有奏效:
指令:
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");
});
});
【问题讨论】:
-
定义“无效”。为什么使用
element.scope.hello()而不仅仅是scope.hello()?此外,element.scope 是一个返回元素范围的函数,如文档所述:docs.angularjs.org/api/ng/function/angular.element。所以应该是element.scope().hello()。 -
与 element.scope().hello() 的结果是一样的:“TypeError: 'undefined' is not a function (evalating 'element.scope().hello()')”
-
还有 scope.hello()。
-
你的指令没有被应用,因为它的默认限制是'A'。所以你需要
<div hello></div>来应用这个指令。如果您希望使用<hello></hello>应用指令,请将限制字段设置为“E” -
没错。另一个命令在测试中失败: beforeEach(module("myApp"));现在它正在工作。如果你把它写在答案中,我会接受。
标签: angularjs unit-testing jasmine karma-runner directive