使用动态模板进行单元测试 angular 指令
Unit testing angular directive with dynamic templates
我有一个指令根据属性中传入的参数选择模板。效果很好,但在我的单元测试中我无法访问 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}
在我看来,单元测试似乎没有正确解析/编译所选模板,但在实际应用程序中一切正常。
谁能告诉我为什么会这样,我该如何解决这个问题?
通常情况下,发布后不久我就找到了解决方案。此 issue https://github.com/angular/angular.js/issues/4505 表明通过用空 div 围绕 ng-include 指令解决了类似的问题。所以我将模板 属性 更改为如下所示:
template: '<div><ng-include src="getTemplateUrl()"/></div>'
现在可以正确编译了。这是一种解决方法,但目前可以使用。
我有一个指令根据属性中传入的参数选择模板。效果很好,但在我的单元测试中我无法访问 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}
在我看来,单元测试似乎没有正确解析/编译所选模板,但在实际应用程序中一切正常。
谁能告诉我为什么会这样,我该如何解决这个问题?
通常情况下,发布后不久我就找到了解决方案。此 issue https://github.com/angular/angular.js/issues/4505 表明通过用空 div 围绕 ng-include 指令解决了类似的问题。所以我将模板 属性 更改为如下所示:
template: '<div><ng-include src="getTemplateUrl()"/></div>'
现在可以正确编译了。这是一种解决方法,但目前可以使用。