gpt4 book ai didi

angularjs - 测试 Angular 指令时出现 Karma 'Unexpected Request',即使使用 ng-html2js

转载 作者:行者123 更新时间:2023-12-02 19:51:40 24 4
gpt4 key购买 nike

在花了最后一天的时间尝试完成这项工作之后,我发现我又回到了开始时遇到的相同错误:

错误:意外请求:GET test-directive.html

我正在使用 Karma 和 Jasmine 来测试 Angular 中的指令。我在 StackOverflow 上查看了类似的问题,但发现在其他示例中尝试过的所有方法都无济于事。

代码结构

测试应用
-src
--凉亭
--lib
--js
--模块
---testDir
----test.js
----测试指令.html
----测试
-----test.spec.js
-测试
--配置
---karma.conf.js
--e2e

Karma 配置

'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'
]
});
};

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();
};
}
};
}]);

test-direct.html

<span>Hello World</span>

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.
});
});
});

已经缩短了几个文件以解决问题所在。在调用 beforeEach(module('dir-templates')) 时,它应该将所有匹配的 .html 文件加载到 $templateCache 中,并阻止引发错误的 GET 请求。

任何帮助将不胜感激,因为它真的让我发疯。如果您还有任何其他问题,请评论。

最佳答案

所以,对于似乎是两行的修复来说是一个令人头痛的问题。在 Chrome(而不是 PhantomJS)中打开 Karma 并查看源文件后,我注意到当 ng-html2js 将指令附加到 $templateCache 时,它​​使用整个路径,而不是指令定义中提供的路径。

简而言之,'src/modules/test/test-directive.html.js' !== 'test-directive.html.js'

要实现此目的,请将 karma.conf.js 文件 ngHtml2JsProcessor 修改为:

ngHtml2JsPreprocessor: {
stripPrefix: 'src/',
moduleName: 'dir-templates'
},

指令声明的 templateUrl 如下所示:

templateUrl: 'modules/test/test-directive.html'

关于angularjs - 测试 Angular 指令时出现 Karma 'Unexpected Request',即使使用 ng-html2js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22869668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com