![](/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.