[英]karma/jasmine/angular – Trouble unit-testing directives AngularJS that use templateUrl
[英]AngularJS testing directives with templateUrl
我正在嘗試使用業力來測試AngularJS指令。 但是我遇到了templateUrls的問題。 使用這里描述的技術,它變得更加陌生。 它看起來像廣告中一樣工作,並將我的模板加載到$ templateCache中,但是該緩存未由指令使用。 這是一些代碼:
這樣就可以了
.directive('messageComposer', function($templateCache) {
return {
restrict: 'E',
template: $templateCache.get('partials/message_composer.html'),
replace: true,
link: function() {
console.log('hello world');
}
};
});
但是一旦我使用templateUrl,它就無法在測試中進行綁定:
.directive('messageComposer', function() {
return {
restrict: 'E',
templateUrl: 'partials/message_composer.html',
replace: true,
link: function() {
console.log('hello world');
}
};
});
有人知道這是怎么回事嗎?
這是我的單元測試設置:
var $scope;
var $compile;
beforeEach(function() {
module('partials/message_composer.html');
module('messageComposer');
inject(function(_$compile_, $rootScope) {
$scope = $rootScope.$new();
$compile = _$compile_;
});
});
it("works", function() {
$scope.message = {};
elem = angular.element("<message-composer message='message'></message-composer>")
$compile(elem)($scope);
console.log(elem);
expect(true).toBeDefined();
});
根據網址( http://tylerhenkel.com/how-to-test-directives-that-use-templateurl/ ),我相信您已運行以下命令:
npm install karma-ng-html2js-preprocessor --save-dev
現在,當您使用上述預處理程序時,該預處理程序會將HTML文件轉換為JS字符串,並生成Angular模塊。 這些模塊在加載時會將這些HTML文件放入$ templateCache中,因此Angular不會嘗試從服務器獲取它們。
希望以下文件能使您更清楚:
https://github.com/karma-runner/karma-ng-html2js-preprocessor https://github.com/vojtajina/ng-directive-testing
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.