简体   繁体   English

测试角度指令时业力“意外请求”,即使使用 ng-html2js

[英]Karma 'Unexpected Request' when testing angular directive, even with ng-html2js

After spending the last day trying to make this work, I've found that I've circled back around to the same error I was having at the beginning:在花了最后一天尝试完成这项工作后,我发现我又回到了开始时遇到的相同错误:

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

I'm using Karma and Jasmine to test directives in Angular.我正在使用 Karma 和 Jasmine 来测试 Angular 中的指令。 I've looked through similar questions on StackOverflow, but find that everything that has been tried in the other examples is to no avail.我在 StackOverflow 上查看了类似的问题,但发现在其他示例中尝试过的所有内容都无济于事。

Code structure代码结构

Test-App测试应用
-src -src
--bower --鲍尔
--lib --lib
--js --js
--modules --模块
---testDir ---测试目录
----test.js ----test.js
----test-directive.html ----test-directive.html
----test - - 测试
-----test.spec.js -----test.spec.js
-test -测试
--config --配置
---karma.conf.js ---karma.conf.js
--e2e --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'
    ]
    });
};

test.js测试.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 test-direct.html

<span>Hello World</span>

test.spec.js测试规范.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.
        });
    });
});

Have shortened a couple of files to stick to just where the issue is.已经缩短了几个文件以坚持问题所在。 In calling beforeEach(module('dir-templates')) , it should be loading all of the matched .html files into the $templateCache and preventing the GET request that is throwing the error.在调用beforeEach(module('dir-templates')) ,它应该将所有匹配的 .html 文件加载到 $templateCache 并防止beforeEach(module('dir-templates'))错误的 GET 请求。

Any help would be appreciated as it's really been driving me nuts.任何帮助将不胜感激,因为它真的让我发疯。 Please comment if you have any additional questions.如果您有任何其他问题,请发表评论。

So, a painstaking headache for what seems to be a two line fix. 所以,这似乎是一个两线修复的痛苦头痛。 After opening Karma in Chrome (instead of PhantomJS) and looking at the source files, I noticed that when ng-html2js attaches the directive to the $templateCache it uses the entire path, not the one provided in the directive definition. 在Chrome中打开Karma(而不是PhantomJS)并查看源文件之后,我注意到当ng-html2js将指令附加到$ templateCache时,它使用整个路径,而不是指令定义中提供的路径。

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

To achieve this, modify the karma.conf.js file ngHtml2JsProcessor to read like: 要实现这一点,请将karma.conf.js文件修改为ngHtml2JsProcessor,如下所示:

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

And the directive declaration's templateUrl to look like: 并且指令声明的templateUrl看起来像:

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

To add to the comments about making sure the template name being matched on matches the prefix (has no leading slash, etc.), one other thing to check for is case. 要添加关于确保匹配的模板名称与前缀匹配的注释(没有前导斜杠等),另外要检查的是另一种情况。

The template cache key is case sensitive, so make sure that your directives are referencing the html files using proper casing. 模板缓存键区分大小写,因此请确保您的指令使用适当的大小写引用html文件。 The template cache keys that the ngHtml2JsPreprocessor generates use the casing of the actual file name and directory names on the file system. ngHtml2JsPreprocessor生成的模板缓存键使用文件系统上实际文件名和目录名的大小写。

So if your file is named Test-Directive.html or your folder is named "Modules" but your directive is referencing "modules/test-directive.html", it won't resolve from the cache. 因此,如果您的文件名为Test-Directive.html,或者您的文件夹名为“Modules”,但您的指令引用了“modules / test-directive.html”,则它将无法从缓存中解析。

Case sensitivity isn't an issue with real (non-test) usage of your directive's templateurl (the GET request obviously is case insensitive and the template cache key will be generated based on whatever the initial GET request was, ie. whatever was specified in your directive). 区分大小写对于指令的templateurl的实际(非测试)使用不是问题(GET请求显然不区分大小写,并且将根据初始GET请求的任何内容生成模板缓存键,即。你的指令)。

Some debugging tips when receiving this error: 收到此错误时的一些调试提示:

When Karma chrome launcher opens the browser, search for the template that is throwing the error, in my case this was student-survey.html , you will see a student-survey.html.js which is the template placed in an angular template cache. 当Karma chrome启动器打开浏览器时,搜索student-survey.html错误的模板,在我的情况下这是student-survey.html ,你会看到一个student-survey.html.js ,这是放置在角度模板缓存中的模板。 Inspecting that html.js file you will see a cache id: $templateCache.put('/app/views/student-survey.html',.... 检查html.js文件,你会看到一个缓存ID: $templateCache.put('/app/views/student-survey.html',....

You must make sure that the cache ID, in this case app/views/student-survey.html will match what is referenced inside your app, in my case the cache id was missing a trailing '/' which i managed to fix by placing a / in the prependPrefix section of the ngHtml2JsPreprocessor section in my karma.conf.js : 你必须确保缓存ID,在这种情况下app/views/student-survey.html将匹配你的应用程序中引用的内容,在我的情况下,缓存ID缺少一个尾随的'/',我设法通过放置来修复在我的karma.conf.js中的prependPrefix部分的ngHtml2JsPreprocessor部分中的a /

ngHtml2JsPreprocessor: { prependPrefix: '/', moduleName: 'templates' }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用templateUrl的指令 - 使用ng-html2js进行测试 - Directive with templateUrl - testing with ng-html2js karma-ng-html2js-preprocessor not working gulp + angular + karma + ng-html2js - karma-ng-html2js-preprocessor not working gulp + angular + karma + ng-html2js 使用ng-html2js进行AngularJS Componet测试 - AngularJS Componet testing with ng-html2js AngularJS + Karma + Ng-html2js =&gt;无法实例化模块... html - AngularJS + Karma + Ng-html2js => Failed to instantiate module …html Karma抛出错误:无法加载“ng-html2js”,它未注册 - Karma throws error: Can not load “ng-html2js”, it is not registered Karma ng-html2js预处理器不生成模块 - Karma ng-html2js preprocessor not generating modules 单元测试angular指令templateUrl(包括requirejs和ng-html2js - unit testing angular directives templateUrl (include requirejs and ng-html2js 错误:意外请求:即使在karma / jasmine单元测试中使用html2js,也可以获取嵌套指令的GET views / partials / * - Error: Unexpected request: GET views/partials/* for a nested directive even when using html2js in karma/jasmine unit test 角度业力测试指令错误:意外请求:GET - Angular karma testing directive Error: Unexpected request: GET 配置karma ng-html2js预处理器以在目录中查找我的模板 - configuring karma ng-html2js preprocessor to find my templates in inside a directory
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM