我有一个简单的 ui-spinner element
指令。
.directive("uiSpinner", function () { // If a size attribute with value large
return { // is present, the spinner will be
restrict: "E", // relatively large.
scope: {
spin: "@",
},
transclude: true,
link: function (scope, element, attrs) {
// NB: scope.size is not linked to the controller scope.
// Because of the compilation process, it will only
// detect static *inline* attributes. This should be
// fine, because this attribute is static in practice.
scope.size = "";
if (attrs.size && attrs.size === "large") {
scope.size = "large-";
}
scope.$watch('spin', function () {
if (scope.spin === "true") {
element.find("#spinner").addClass(scope.size + "spin");
} else {
element.find("#spinner").removeClass(scope.size + "spin");
}
});
},
template: "<div id='spinner'><div></div> </div>"
};
})
在测试设置中,我试图验证它是否只有一个子项。
describe('uiSpinner', function () {
describe('template', function () {
beforeEach(function () {
directiveTemplate = "<ui-spinner spin='{{is_spinning}}'>" +
'</ui-spinner>';
compiledEl = $compile(directiveTemplate)($scope);
});
iit("is comprised of a single element", function () {
expect(compiledEl.find("*").length).toBe(2);
});
});
...
我之前尝试过使用 compiledEl.children().length
对此进行测试,但它总是返回 1。我也尝试过将compileEl 包装在 $
或 中angular.element
,结果仍然相同。基本上,为什么我需要使用迟钝的 .find("*")
而不是使用 .children()
来选择指令的子项?
最佳答案
当你这样做时compiledEl.children()
它总是返回 1,因为唯一的 child 是 <div id='spinner'></div>
.
如果您要查找的是 #spinner
的子级数量div,你需要做compiledEl.children().eq(0).children().length
或compiledEl.find('#spinner').children().length
.
关于javascript - Angular.js - 测试元素指令中的子元素数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20807833/