我正在尝试以 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/