![](/img/trans.png)
[英]karma/jasmine/angular – Trouble unit-testing directives AngularJS that use templateUrl
[英]Unit testing of Angular directives with templateUrl and WITHOUT Karma
我在这里找到了一种解决方案,该解决方案涉及如何不使用Karma从templateUrl加载模板,因此我已将此代码粘贴到我的beforeEach()并添加了检查测试:
beforeEach(inject(function ($templateCache,_$compile_, _$rootScope_, $injector, _config_, _$timeout_) {
var directiveTemplate = null;
var req = new XMLHttpRequest();
req.onload = function () {
directiveTemplate = this.responseText;
};
req.open("get", "js/directives/views/questionnaire-list.html", false);
req.send();
$templateCache.put("js/directives/views/questionnaire-list.html", directiveTemplate);
$compile = _$compile_;
$rootScope = _$rootScope_.$new();
$rootScope.questionnaires = questionnaire;
$rootScope.touchDisabled = jasmine.createSpy('touchDisabled');;
$rootScope.onChange = jasmine.createSpy('onChange');;
$rootScope.renderingFinished = jasmine.createSpy('renderingFinished');;
$httpBackend = $injector.get('$httpBackend');
config = _config_;
}));
it('compiled should not be empty', function () {
element = angular.element('<questionnaire-list questionnaires = "questionnaires" touch-disabled = "touchDisabled()" on-change = "onChange()" rendering-finished = "renderingFinished()"></questionnaire-list>');
var result = $compile(element)($rootScope); // Compile the directive
$rootScope.$digest(); // Update the HTML
var items = result.html();
expect(items).not.toEqual("");
});
但这等于“”。 我究竟做错了什么? 我对测试指令和angularjs本身是全新的,所以我认为我在使用templateCache时误解了。
指令代码:
angular.module('app.directives')
.directive('questionnaireList', questionnaireList);
questionnaireList.$inject = ['$timeout'];
function questionnaireList($timeout) {
return {
restrict: 'A',
templateUrl: 'js/directives/views/questionnaire-list.html',
scope: {
questionnaires: '=',
touchDisabled: '&',
onChange: '&',
renderingFinished: '&'
},
link: link
}
function link(scope, element, attrs) {
// some code goes here
}
}
和templateUrl:
<div ng-repeat="questionnaire in questionnaires" children-same-size on-render="onContentRendered">
{{questionnaire.Title}}
<div ng-repeat="item in questionnaire.Questions" class="questions-list-item">
<div class="question-control"><!--some text--></div>
<div class="captions">
<span ng-repeat="label in ::getQuestionLabels(item)">{{::label}}</span>
</div>
</div>
提前致谢!
通过将element
更改为<div questionnaire-list="" questionnaires = "questionnaires" touch-disabled = "touchDisabled()" on-change = "onChange()" rendering-finished = "renderingFinished()"></div>
。 现在, items
不为空,并且包含正确的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.