【发布时间】:2015-11-12 01:42:18
【问题描述】:
我正在使用 Jasmine 为 angularJS 中的指令编写测试。在 karma.conf.js 中,我包含了所有依赖项和模块的路径。我正在使用的指令非常复杂,因此我借用了一些简单的自定义指令代码进行测试。它在我的应用程序中的 js fiddle 和指令函数中运行良好,但它在我的应用程序中未通过以下测试:
我的规范看起来像这样:
describe('Unit testing: ', function() {
var $compile,
$rootScope;
beforeEach(module('app.directives')); // our directives
// Store references to $rootScope and $compile
// so they are available to all tests in this describe block
beforeEach(inject(function(_$compile_, _$rootScope_){
// The injector unwraps the underscores (_) from around the parameter names when matching
$compile = _$compile_;
$rootScope = _$rootScope_;
}));
it('Replaces the element with the appropriate content', function() {
// Compile a piece of HTML containing the directive
var element = $compile("<div hello-world></div>")($rootScope);
// fire all the watches, so the scope expression {{1 + 1}} will be evaluated
$rootScope.$digest();
// Check that the compiled element contains the templated content
expect(element.html()).toContain("Hello World!");
});
});
指令如下所示:
angular.module('app.directives')
.directive('helloWorld', function() {
return {
restrict: 'AE',
template: '<h3>Hello World!!</h3>'
};
});
当我运行 grunt karma 时,最后一个测试失败了,因为:
Firefox 40.0.0 (Mac OS X 10.10.0) Unit testing: Replaces the element with the appropriate content FAILED
Expected '' to contain 'Hello World!'.
我在插入一些 console.log 语句时看到的主要问题是,在我调用 $compile 之后(或在 $digest 之后)指令没有正确编译:
Firefox 40.0.0 (Mac OS X 10.10.0) LOG: {0: <div class="ng-scope" hello-world=""></div>, length: 1}
我很困惑。我知道我可能需要提供有关我的应用程序的更多信息,但简而言之,这种解释是我的核心问题。
[编辑]:创建一个新模块可以快速解决这个问题,但问题仍然是当单个模块中有多个指令时如何处理指令单元测试(仍然失败)。
【问题讨论】:
-
你的指令名称是 "mmsHelloWorld" 那么你的模板不应该看起来像
<div mms-hello-world></div>吗?即,您缺少mms-前缀 -
mms 只是特定于我正在处理的应用程序的命名约定。我试图概括代码并使其更直观,所以我删除了它,但显然不是全部!对不起!
-
你的指令名称应该是 "helloWorld",而不是 "HelloWorld" 虽然我不完全确定前导大写字母是否有区别但比抱歉更安全:)
-
你是对的,但这也是命名约定编辑的一部分。在发布代码之前我应该更加注意:(。
-
啊,我是
replace: 'false'。'false'字符串的计算结果为true。要么设置replace: false,要么完全省略replace(反正它已经被弃用了)
标签: angularjs jasmine karma-runner