我正在使用Jasmine为angularJS中的指令编写测试。在karma.conf.js中,我已经包含了所有依赖项和模块的路径。我正在使用的指令非常复杂,所以我借用了一些简单的自定义指令代码用于测试目的。它在js小提琴和我的应用程序中的指令函数中工作得很好,但它在我的应用程序中未通过测试:
我的规范看起来像这样:
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业力时,最后一次测试失败,因为:
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}
我很难过。我知道我可能需要提供更多关于我的应用程序的信息,但这个解释是我的核心问题。
[编辑]:创建一个新模块是对此的快速解决方案,但问题仍然是如何在单个模块中存在多个指令时仍然如何处理指令单元测试(仍然失败)。
答案 0 :(得分:1)
(答案已编辑) 一旦我确定它正确地包含在我的karma.conf.js中,你的代码就能为我工作。
files: [
"include/path/to/your/directive/file.js",
"include/path/to/your/directive/test.js"
]