javascript - 即使在运行digest()之后,在测试中编译 Angular Directive(指令)也会失败

标签 javascript angularjs

我正在尝试以 Angular Testing 指令,但即使在运行 $scope.$digest() 之后,编译也无法正常工作。

该指令的模板如下所示:

<div>
    <knob>...</knob>
    <knob>...</knob>
    <knob>...</knob>
</div>

测试看起来像这样:

describe('DirectiveTest', function() {

    beforeEach(module('AppTestModule'));

    var directiveElem, $scope;

    beforeEach(inject(function ($rootScope, $compile, $q, $injector, $templateCache) {

        $scope = $rootScope.new();

        $scope.parameter1 = {};
        $scope.parameter2 = {};
        $scope.parameter3 = false;

        directiveElem = angular.element('<my-directive param1="parameter1" param2="parameter2" param3="parameter3"></my-directive>');
        $compile(directiveElem)($scope);

        $scope.$digest();

    }));

    it('should have three knobs', function() {
        $scope.$digest();
        console.log('directiveElem = ', directiveElem);
        var knobs = directiveElem.find('knob');
        expect(knobs.length).toEqual(3);
    });

});

测试失败(没有找到任何 knob 元素),因为未编译该指令。

console.log 打印如下内容:

directiveElem = ', {0: <my-directive param1="parameter1" param2="parameter2" param3="parameter3" class="ng-scope"></my-directive>, length: 1}

(它只添加 class="ng-scope")

值得注意的是,我正在使用 ng-html2js karma 预处理器,并且我发现 Chrome 中正在加载模板

最佳答案

不确定为什么要使用angular.element(...)。我通常使用这样的东西:

var elementHtml = '<my-directive></my-directive>';
element = $compile(elementHtml)(scope);
scope.$digest();

要查看生成的 html,您可以使用:

console.log(element.html());

关于javascript - 即使在运行digest()之后,在测试中编译 Angular Directive(指令)也会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32233635/

相关文章:

javascript - 我如何保持弹出 div 始终打开,即使在页面刷新/重新加载时也是如此,直到用户使用 HTML5 本地存储将其关闭

javascript - 编码不当的 JQuery : naming dependancies

javascript - 在加载文档之前隐藏图像,然后对其应用效果

javascript - ASP.net 样板 - 范围

javascript - 如何在页面提交时自动滚动到页面顶部

javascript - 在 jQuery 克隆中查找元素

javascript - 如何通过 JSON/JS 在 Jenkins 中为 CSRF 添加面包屑

javascript - 在 `$scope` 或 `this` 上定义的 Controller 函数之间的性能差异 - AngularJS

javascript - 在php中使用服务器发送事件从mysql获取数组

javascript - 如何使用 AngularJS 将 DELETE 请求发送到带有 Json 数据的服务器?