【发布时间】:2014-05-01 20:54:48
【问题描述】:
我在 Karma 中运行我的 jasmine 单元测试时遇到问题,而我的一个依赖于外部模板(AngularJS 指令)的单元测试没有通过。当我在浏览器中进入调试模式并查看控制台时,它显示此单元测试正在通过,当我在浏览器调试器中逐步完成单元测试时,我可以确认这一点。
我还有其他单元测试也依赖于外部模板,这些模板按预期传入 Karma,但只是这个特定测试在 Karma 中失败,但通过了浏览器控制台。
有没有人知道是什么导致了这种行为?
编辑:
Karma 显示如下:
TypeError: Unable to get value of the property 'then': object is null or undefined
我的项目处理模板与 AngularJS 通常处理它们的方式略有不同。我们创建了一个 templateService,它根据如下所示的指令的 templateUrl 检索正确的模板
templateUrl: "navigation-template"
所以我设置了 Karma 来提取模板并将它们存储在 templateCache 中。然后我使用使用的键 Karma(文件路径)提取模板,并使用指令所期望的 templateUrl 将它们重新插入到 templateCache 中。这是我的做法
var template = '<div>' + templateCache.get(templateFilePath) + '</div>'; }
// template files contain multiple templates so this filters out the one I want
template = $("[TemplateId='" + directiveTemplateUrl + "']", template).html();
templateCache.put(directiveTemplateUrl, template);
对于所有其他测试,这工作正常,但特别是产生上述错误。更有趣的是,如果我像这样添加控制台日志
var template = '<div>' + templateCache.get(templateFilePath) + '</div>';
if (template.indexOf("undefined") > -1) { throw new Error("Template not in cache."); }
template = $("[TemplateId='" + directiveTemplateUrl + "']", template).html();
if (!template) { throw new Error("Template not found."); }
templateCache.put(directiveTemplateUrl, template);
它会注销未找到模板。
Error: Template not in cache.,Error: Unexpected request: GET navigation-template No more request expected
如果我在浏览器中调试(Karma 加载浏览器时的调试按钮),我可以确认模板存在并且在浏览器控制台中(不是运行 Karma 的命令行,而是浏览器中的 F12 开发人员工具) 它会像这样注销测试成功
LOG: SUCCESS ButtonsDirectives NavigationDirective Should render a loading message
这是我所知道的:
失败的单元测试和通过的单元测试之间没有显着差异。它与单元测试的运行顺序无关(这个只是碰巧先运行)。
【问题讨论】:
-
“通过浏览器控制台”是什么意思,测试失败时出现的错误是什么?当您在调试器中单步执行代码时它通过了这一事实,这听起来像是一个时间问题。
-
您能发布浏览器控制台中的内容吗?
-
@SunilD。我认为“DEBUG”是指Karma中的调试窗口,而不是JS调试器。
-
编辑了原始帖子以包含更多信息。
-
这可能是一个时间问题:您可以跟踪模板加载过程中的所有步骤吗?它是使用承诺的 Angular 指令吗?它可能无法实例化/正确使用...
标签: angularjs unit-testing angularjs-directive jasmine karma-runner