我们有一个带有可选属性的指令。如果该属性不存在,它将提供默认值。该属性通常是根据范围内的数据设置的(即,属性的值通常是表达式而不是文字字符串。请参阅 http://jsfiddle.net/8PGZ4/
因此,我们在指令中使用 attrs.$observe
来正确设置范围。这在应用程序本身中效果很好。然而,当尝试测试这个(使用 Jasmine)时,$observe 中的函数永远不会运行。我们的测试看起来像这样:
describe("myDirective", function(){
function getDirectiveScope(compile, rootScope, directiveHTML)
{
return (compile(directiveHTML)(rootScope)).scope();
}
describe("foo", function () {
it("should return the default value", inject(function ($compile, $rootScope) {
var directiveScope = getDirectiveScope($compile, $rootScope, '<div my-directive></div>');
expect(directiveScope.bar).toBe("No Value");
}));
it("should now return the value given", inject(function ($compile, $rootScope) {
$rootScope.foo = "asdf";
var directiveScope = getDirectiveScope($compile, $rootScope, '<div my-directive foo="{{foo}}"></div>');
expect(directiveScope.bar).toBe("asdf");
}));
});
});
然后这些会失败并出现以下错误:
Expected undefined to be 'No Value'.
Expected undefined to be 'asdf'.
我在 $observe
函数中放置了一个 console.log 来尝试查看发生了什么,但当测试运行时,我从未看到日志。我是否必须进行显式调用才能运行 $observe
?这里还有其他事情发生吗?
最佳答案
您需要触发一个摘要周期,让 AngularJS 的魔力在您的测试中发生。尝试:
it("should return the default value", inject(function ($compile, $rootScope) {
var directiveScope = getDirectiveScope($compile, $rootScope, '<div my-directive></div>');
$rootScope.$digest();
expect(directiveScope.bar).toBe("No Value");
}));
关于javascript - 在我的测试中 $observe 函数从未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13690680/