[英]Unit testing an Angular Directive
我正在尝试使用karma和jasmine对所有指令进行单元测试。 当我尝试加载一个名为header.html
的模板的指令时,我收到以下错误: Error: Unexpected request: GET header.html No more request expected
http://plnkr.co/edit/YTUFXCMdK5JFEwMzzXaR?p=preview
更新:我在karma.conf.js中有以下配置:
files: [
'test/client/specs/main.js',
// 'WebContent/modules/common/header/**/*.html',
{pattern: 'WebContent/libs/**/*.js', included: false},
{pattern: 'WebContent/modules/**/*.js', included: false},
{pattern: 'WebContent/modules/common/header/tmpl/*.html', included: false},
{pattern: 'test/client/specs/**/*spec.js', included: false}
],
// generate js files from html templates
preprocessors: {
'WebContent/modules/common/header/**/*.html': ['ng-html2js']
},
ngHtml2JsPreprocessor: {
'moduleName': 'Templates',
cacheIdFromPath: function(filepath) {
return filepath.match(/\/WebContent\/modules\/common\/header\/.*\.html/);
}
},
我正在尝试加载它:
beforeEach(function() {
module("Templates");
});
现在我收到以下错误:
Error: [$injector:modulerr] Failed to instantiate module Templates due to:
Error: [$injector:nomod] Module 'Templates' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
http://errors.angularjs.org/1.2.12/$injector/nomod?p0=Templates
Karma方式是将模板html动态加载到$ templateCache中。 你可以只使用html2js
因缘预处理器,如解释在这里
这归结为将模板'* .html'添加到conf.js文件中的文件中
preprocessors = {
'*.html': 'html2js'
};
并使用
beforeEach(module('..'));
beforeEach(module('...html', '...html'));
进入你的js测试文件
我在单元测试中解决了这个问题,方法是将$ templateCache注入测试,然后将html放入缓存中。
http://plnkr.co/edit/btgYfiiRzacS6MfPFlbv?p=preview
我研究了几种不同的方法,然后我们决定将html放入指令中。
template: "<div>This is the template</div>"
它使得测试变得更加容易,因为您不再需要在单元测试中更新templateCache,这在您的指令中有大量的html时会很容易出错并且容易出错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.