我正在开发一个还不大的 Angular 应用程序。我在 karma 单元测试方面遇到了问题。长话短说,我将 Angular 与 requirej 一起使用。如果我将模板嵌入到指令中,我的测试就会运行良好。但由于这个应用程序非常庞大,因此无法扩展。但是,当我移动模板并使用 templateUrl
将其加载到我的指令中时,我无法消除以下错误之一(取决于我如何修改conf):
(初始错误)“意外请求:GET path/to/mytpl.html”
“ReferenceError:找不到变量: Angular ”。不同的配置会发生此错误:
- 当我将
{pattern: 'path/to/mytpl.html', Included: false}
放入我的 karma.conf 并添加 requirejs 的定义path/to/mytpl.html
在我的测试文件中(这是我希望的工作方式)。 - 当我将
path/to/mytpl.html
放入 karma.conf 时,我的所有模板都会返回此错误(无论我是否使用 ng-html2-js 预处理器)。
- 当我将
“错误:[$injector:modulerr] 无法实例化模块模板,原因是: 错误:[$injector:nomod] 模块"template"不可用!”。我看到 karma-ng-html2js-preprocessor 可用于创建一个包含所有模板的模块,但它从未起作用。
注意:我不在 karma.conf 中使用 FQN,我在这里使用它是为了保持一致。我认为这并不重要,但我更喜欢精确
我看到有人将每个 'path/to/mytpl.html': {deps: ['angular']}
放在 test-main.js 的 shim 部分中。但它对我不起作用,并且该解决方案无法扩展。
最佳答案
我遇到了同样的问题,并在以下article中找到了解决方案。 我猜你的问题是错误的 karma 或 requireJS 配置,特别是基本路径设置。 如果您的指令 templateUrl 是相对的,并且该 url 无法根据 karma 基本路径或 requireJS 基本路径正确解析,那么您需要解决此问题。
假设您的指令的 templateUrl 值为“app/directive/myDirective.html”。然后:
检查您的 html 文件是否正确包含到 karma 配置的 files 部分,注意 included:false 设置:
files: [ //... { pattern: 'path_to_directive/myDirective.html', included: false }, //... ],
当然,您可以使用 * 或 ** 等通配符,但出于故障排除的目的,我将从完整路径值开始。根据 karma 配置中的 basePath 值,'path_to_directive' 将与应用中的路径相同或不同。
例如:如果 karma 基本路径比您的应用根目录高一级,则您的 'path_to_directive' = 'some-folder/app/directive/myDirective.html'
<确保您可以从浏览器获取文件。前往http://localhost:karma_port/base/path_to_directive/myDirective.html.js
进行此测试时请注意:
- 网址中的base前缀(karma 为该虚拟路径中的所有文件提供服务,并将此前缀添加到所有网址中)
- '.js' 位于网址末尾
在步骤 2 中获取文件后,您将看到由 html2js 预处理器创建的实际模块代码。它应该看起来像这样:
angular.module('module_path/myDirective.html', []).run(function($templateCache) { $templateCache.put('module_path/myDirective.html', //...
确保 module_path 为“app/directive/”。如果没有,那么您有 2 个选择:
module_path 有一些前缀 => 只需将以下内容添加到 karma 配置中即可将其删除:
ngHtml2JsPreprocessor: { stripPrefix: 'modulePrefix' }
module_path 更短 => 添加缺失的部分:
ngHtml2JsPreprocessor: { prependPrefix: 'missingPart' }
重新启动 karma 并确保第 3 步中的'module_path'为'app/directive/'
确保您已为模板模块添加了 Angular 依赖项(检查 test-main.js,它基本上是 requireJS 的配置文件)。另请记住,shim 部分中的值将根据 test-main.js 文件中的 baseUrl 值进行解析。为简单起见,我假设 requireJS 可以从“requirejs_path/myDirective.html”路径获取文件。
shim: { //.. 'requirejs_path/myDirective.html': { deps: ['angular'] }, //.. }
确保您已将模板作为测试的依赖项包含在内,并且不要忘记加载模块:
define(['requirejs_path/myDirective.html', 'angular-mocks', '...'], function () { describe('test suite', function() { //... beforeEach(module('app/directive/myDirective.html')); //... }); });
我希望通过完成这 6 个步骤,您将获得有效的测试。祝你好运。
关于angularjs - 单元测试 Angular 指令 templateUrl (包括 requirejs 和 ng-html2js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25431254/