【问题标题】:Unit testing angular directive with dynamic templates使用动态模板对角度指令进行单元测试
【发布时间】:2015-03-30 00:00:27
【问题描述】:

我有一个指令,它根据属性中传入的参数选择模板。它工作得很好,但在我的单元测试中我无法访问 DOM。

指令模板行如下所示:

template: '<ng-include src="getTemplateUrl()"/>'

指令控制器有这个:

$scope.getTemplateUrl = function () {
                    var template;
                    switch( $scope.layout ) {
                        case "addLocation":
                            template = 'app/search/primarySearchControlsAddLocation.html';
                            break;
                        default:
                            template = 'app/search/primarySearchControlsSidebar.html';
                    }
                    return template;
                };

单元测试如下所示:

it( 'Should disable the client control when the disableClientSelect field param is true. ', function () {
            element = $compile( angular.element( '<primary-search-controls b-disable-client-select="true" layout="searchSidebar"></primary-search-controls>') )( $rootScope );
            $rootScope.$apply();
            expect( element[ 0 ].find( 'input.client-typeahead' ) ).to.have.class( 'disabled' );
        });

当我在这个测试期间转储出元素的值时,我得到了这个:

LOG: {0: <!-- ngInclude: undefined -->, length: 1}

在我看来,单元测试似乎没有正确解析/编译所选模板,但在实际应用程序中一切正常。

谁能指出为什么会发生这种情况以及如何解决这个问题?

【问题讨论】:

    标签: javascript angularjs unit-testing angularjs-directive


    【解决方案1】:

    通常情况下,在发布后不久,我找到了解决方案。这个 issue https://github.com/angular/angular.js/issues/4505 建议通过用空 div 包围 ng-include 指令来解决类似的问题。所以我将我的模板属性更改为如下所示:

    template: '<div><ng-include src="getTemplateUrl()"/></div>'
    

    现在它可以正确编译了。这是一种解决方法,但现在可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-16
      • 2013-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多