dma*_*alu 25 unit-testing angularjs angularjs-directive karma-runner
在最后一天尝试完成这项工作之后,我发现我已经绕回到我在开始时遇到的同样错误:
错误:意外请求:GET test-directive.html
我正在使用Karma和Jasmine来测试Angular中的指令.我在StackOverflow上查看了类似的问题,但发现在其他示例中尝试过的所有内容都无济于事.
代码结构
Test-App
-src
--bower
--lib
--js
--modules
--- testDir
---- test.js
---- test-directive.html
---- test
----- test.spec .js文件
-test
--config
--- karma.conf.js
--e2e
Karma Config
'use strict';
module.exports = function(config){
config.set({
basePath: '../../',
frameworks: ['jasmine'],
files: [
// Angular
'src/bower/angular/angular.js',
// Mocks
'src/bower/angular-mocks/angular-mocks.js',
// Libraries
'src/lib/**/*.js',
// App
'src/js/*.js',
'src/modules/*/*.js',
// Tests
'src/modules/**/test/*spec.js',
// Templates
'src/modules/**/*.html'
],
autoWatch: false,
singleRun: true,
reporters: ['progress'],
browsers: ['PhantomJS'],
preprocessors: {
'src/modules/**/*.html': 'ng-html2js'
},
ngHtml2JsPreprocessor: {
moduleName: 'dir-templates'
},
plugins: [
'karma-jasmine',
'karma-ng-html2js-preprocessor',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-junit-reporter'
]
});
};
Run Code Online (Sandbox Code Playgroud)
test.js
'use strict';
angular.module('modules.test', []).
directive('testDirective', [function() {
return {
restrict: 'E',
templateUrl: 'test-directive.html',
link: function($scope, $elem, $attrs) {
$scope.someFn = function() {
angular.noop();
};
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
测试direct.html
<span>Hello World</span>
Run Code Online (Sandbox Code Playgroud)
test.spec.js
'use strict';
describe('test module', function() {
beforeEach(module('modules.test'));
/* -- DIRECTIVES------------------ */
describe('directives', function() {
var $compile, $scope, elm;
beforeEach(module('dir-templates');
beforeEach(inject(function($compile, $rootScope) {
$scope = $rootScope.$new();
elm = angular.element('<test-directive></test-directive>');
$compile(elm)($scope);
$scope.$digest();
}));
it('should have one span tag', function(){
//Jasmine test here to check for one span tag.
});
});
});
Run Code Online (Sandbox Code Playgroud)
已经缩短了几个文件以确定问题所在.在调用时beforeEach(module('dir-templates'))
,它应该将所有匹配的.html文件加载到$ templateCache中,并防止抛出错误的GET请求.
任何帮助将不胜感激,因为它真的让我疯了.如果您有任何其他问题,请发表评论.
dma*_*alu 29
所以,这似乎是一个两线修复的痛苦头痛.在Chrome中打开Karma(而不是PhantomJS)并查看源文件之后,我注意到当ng-html2js将指令附加到$ templateCache时,它使用整个路径,而不是指令定义中提供的路径.
简而言之,'src/modules/test/test-directive.html.js' !== 'test-directive.html.js'
.
要实现这一点,请将karma.conf.js文件修改为ngHtml2JsProcessor,如下所示:
ngHtml2JsPreprocessor: {
stripPrefix: 'src/',
moduleName: 'dir-templates'
},
Run Code Online (Sandbox Code Playgroud)
并且指令声明的templateUrl看起来像:
templateUrl: 'modules/test/test-directive.html'
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11004 次 |
最近记录: |