【问题标题】:karma-ng-html2js-preprocessor not creating moduleskarma-ng-html2js-preprocessor 不创建模块
【发布时间】:2015-12-16 00:08:19
【问题描述】:

尝试使用 karma-ng-html2js-preprocessor。 Karma 发现我所有其他的东西(javascript)都很好,但是当涉及到这个 html 预处理器时,它似乎无法找到并从中生成模块。

在下面查看我的选项对象。如您所见,我在 files 属性中添加了一个模式,并且我为模块使用了通用名称“foo”。在测试中,每当我尝试调用 module('foo'); 时,业力都会引发错误 我真的希望能够使用它,这样我就不必将模板硬编码到我的单元测试或其他一些古怪的解决方案中。

    var options = {
        files: [].concat(
            bowerFiles,
            config.specHelpers,
            clientApp + '**/*.module.js',
            clientApp + '**/*.js',
            clientApp + '**/*.html',
            '*.html',
            temp + config.templateCache.file,
            config.serverIntegrationSpecs
            ),
        exclude: [],
        coverage: {
            dir: report + 'coverage',
            reporters: [
                // reporters not supporting the `file` property
                { type: 'html', subdir: 'report-html' },
                { type: 'lcov', subdir: 'report-lcov' },
                { type: 'text-summary' } //, subdir: '.', file: 'text-summary.txt'}
            ]
        },
        ngHtml2JsPreprocessor: {
            // strip this from the file path
            // stripPrefix: clientApp,
            moduleName: 'foo'
        },
        preprocessors: {}
    };
    options.preprocessors[clientApp + '**/*.html'] = ['ng-html2js'];
    options.preprocessors[clientApp + '**/!(*.spec)+(.js)'] = ['coverage'];
    return options;
}

【问题讨论】:

  • 您的preprocessors 密钥'*.html' 可能与clientApp + '**/*.html' 中的任何内容都不匹配。尝试使用相同的模式,甚至只使用'**/*.html'?
  • 你说得对,我实际上在你评论的同时把它改成了那个,但这似乎并没有解决它。我已经更新了我的原始帖子以显示选项对象现在的样子。
  • templateUrl 属性中的路径是否包含 clientApp 的任何内容?例如,假设clientApp = 'myApp/src',您的templateUrl 属性是否类似于'myApp/src/path/to/template.html'
  • clientApp = "./src/client/app/" templateUrl: "src/client/app/orders/' 但我也试过没有clientApp...
  • 如果您使用真正的浏览器(不是 Phantom)启动 Karma,您可以查看页面源代码并查看包含的脚本文件。查看您的模板以及用于将它们添加到$templateCache 的路径/键。它们是否与templateUrl 中的值匹配?

标签: javascript angularjs unit-testing karma-runner


【解决方案1】:

我知道这不一定能回答您的问题,如果发现更多信息,我会在此答案中添加内容,但我发现此策略效果很好...

我发现指令、路由或状态的 HTML 模板(如果使用 ui-router)在单元测试时不应该发挥作用。单元测试是关于测试你的组件的接口;其公开可用的方法和属性。测试与 HTML 文档的交互实际上属于使用量角器之类的端到端测试领域。

考虑到这一点,下面是我阻止 Karma 在测试期间尝试加载模板文件的方法。

beforeEach(function() {
    module('module.name.of.the.testable.component');

    inject(function($templateCache) {
        $templateCache.put('path/to/template/as/it/appears/in/your/component.html',
            '<div></div>');
    });
});

【讨论】:

  • 这很酷,除非我的模板相对较大(它不是很大,但足够大以至于在代码中会很烦人)并且您不想费心维护代码在两个不同的地方?
  • @z0d14c 我实际上的意思是使用'&lt;div&gt;&lt;/div&gt;' 作为$templateCache 条目。在单元测试时,模板真的不重要。这只是为了阻止 Karma 尝试加载 HTML 文件。
  • 好吧,如果我想测试模板的一个属性(就像它存在一样),呃,这无关紧要吗?
  • @z0d14c 像什么?您可以轻松地测试分配给范围或控制器的属性,如果您正在寻找指令中的 DOM 操作,您可以随时监视(假设 Jasmine)element 方法
猜你喜欢
  • 1970-01-01
  • 2016-12-27
  • 2014-11-19
  • 1970-01-01
  • 2013-10-22
  • 1970-01-01
  • 2013-10-04
  • 2016-02-28
  • 2019-09-04
相关资源
最近更新 更多