javascript - Angular.js - 测试元素指令中的子元素数量

标签 javascript jquery angularjs

我有一个简单的 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>&nbsp;</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().lengthcompiledEl.find('#spinner').children().length .

关于javascript - Angular.js - 测试元素指令中的子元素数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20807833/

相关文章:

javascript - 在 HTTP 请求 AngularJS 之后将数据从工厂返回到 Controller

javascript - 加了Tampermonkey的onclick是不是调用了函数?

javascript - 根据内容更改 ng-repeat 内输入的 ng-model

javascript - 对象回调函数未定义 Javascript

javascript - 替换后动画至高度 0

javascript - 将网页文本中的匹配词更改为按钮

jQuery - 可缩放的可拖动 div

javascript - AngularJS指令: how to compile html after promise

javascript - 如何在javascript中复制构造函数中的对象

javascript - Angular2 : AsyncPipe and Observable, 无法检索属性(TypeError : Cannot read property . .. of null)