Angular.js - 测试element指令中的子项数

时间:2013-12-27 21:06:49

标签: 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.我也尝试在$angular.element中包装编译的E1,结果仍然相同。基本上,为什么我需要使用钝.find("*")而不是使用.children()来选择我的指令的子项?

1 个答案:

答案 0 :(得分:4)

当你执行compiledEl.children()时,它总是返回1,因为唯一的孩子是<div id='spinner'></div>

如果您要查找的是#spinner div的子女数,则需要compiledEl.children().eq(0).children().lengthcompiledEl.find('#spinner').children().length