Сбой директивы компиляции в тестировании AngularJS - Карма Жасмин
Я использую Karma с Jasmine Framework для тестирования моего приложения AngularJS v1. Я установил плагин ng-html2js для преобразования партиалов в модуль. Я могу получить доступ к частичным с помощью $templateCache
,
Когда я пытаюсь скомпилировать директиву, я ничего не получаю. Шаблон для URL указывается с помощью templateUrl
,
Моя структура проекта как таковая.
project
|--index.php
|--karma.conf.js
|--assets
|--app
|--controllers
|--directives
|--my-directive.js
|--partials
|--my_directive.html
|--tests
|--directive-test.js
karma.conf.js
...
preprocessors: {
"assets/app/partials/**/*.html": ['ng-html2js']
},
files: [
...
'assets/app/controllers/**/*.js',
'assets/app/directives/**/*.js',
'assets/app/partials/**/*.html',
'assets/app/tests/**/*.js',
],
ngHtml2JsPreprocessor: {
moduleName: 'my.partials'
},
...
Директива-test.js
describe('Test My Directive', function () {
var $compile, $rootScope;
beforeEach(function () {
module('myapp');
module('my.partials');
inject(function (_$compile_, _$rootScope_, _$templateCache_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$templateCache = _$templateCache_;
// This prints the template to the console
console.log($templateCache.get('assets/app/partials/my_directive.html'));
});
});
it('check if directive compiles', function () {
var scope = $rootScope.$new();
var template = $compile('<my-directive></my-directive>')(scope);
scope.$digest();
var templateAsHtml = template.html();
// This doesn't print the template to the console
console.log('templateAsHtml', templateAsHtml);
expect(templateAsHtml).toContain("Lorem ipsum");
});
});
мой-directive.js
myapp.directive('myDirective', function() {
return {
replace:true,
restrict:'E',
templateUrl: 'assets/app/partials/my_directive.html',
link: function (scope, element, attrs) {
console.log('my directive');
}
}
});
активы / приложение / обертоны / директивы /my_directive.html
<div><h2>Test Directive</h2><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam et enim non sem bibendum maximus. Nunc at urna sit amet.</p></div>
2 ответа
Я решил это таким образом - благодаря подсказкам от @Aaron Pool. С помощью templateUrl
в директивах делает асинхронный запрос / AJAX-вызовы для извлечения шаблона. $http AJAX-вызовы могут быть перехвачены с помощью $httpBackend. Захватите вызов AJAX и ответьте шаблоном из $templateCache
, Вот модифицированный код, предполагая, $httpBackend
был введен в beforeEach()
блок.
it('check if directive compiles', function () {
var scope = $rootScope.$new();
// Intercept the AJAX to fetch template
$httpBackend.whenGET('assets/app/partials/directives/my_directive.html')
.respond($templateCache.get('assets/app/partials/directives/my_directive.html'));
var template = $compile('<my-directive></my-directive>')(scope);
$httpBackend.flush();
scope.$digest();
var templateAsHtml = template.html();
// Now it prints the template to the console
console.log('templateAsHtml', templateAsHtml);
expect(templateAsHtml).toContain("Lorem ipsum");
});
Если я правильно помню, templateUrl всегда является асинхронным запросом, даже если указанный URL-адрес уже находится в $templateCache. Попробуйте это вместо этого в своем определении директивы:
template: function($templateCache) {
return $templateCache.get('assets/app/partials/my_directive.html');
}