Javascript 角度指令的单元测试
我试图使用karma和jasmine对所有指令进行单元测试。当我尝试加载一个指令时,该指令有一个名为Javascript 角度指令的单元测试,javascript,angularjs,unit-testing,ng-html2js,Javascript,Angularjs,Unit Testing,Ng Html2js,我试图使用karma和jasmine对所有指令进行单元测试。当我尝试加载一个指令时,该指令有一个名为header.html的模板,我得到以下错误:错误:意外请求:get header.html不需要更多请求 更新: 我在karma.conf.js中有以下配置: files: [ 'test/client/specs/main.js', // 'WebContent/modules/common/header/**/*.html', {pattern: 'We
header.html
的模板,我得到以下错误:错误:意外请求:get header.html不需要更多请求
更新:
我在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
karma预处理器,如前所述
这归结为将模板“*.html”添加到conf.js文件中的文件中
也
和使用
beforeEach(module('..'));
beforeEach(module('...html', '...html'));
在js测试文件中我在单元测试中解决了这个问题,将$templateCache注入测试,然后将html放入缓存 我研究了几种不同的方法,我们决定将html放入指令中
template: "<div>This is the template</div>"
模板:“这是模板”
它使测试变得更加容易,因为您不再需要在单元测试中更新templateCache,这是一个麻烦,而且当您的指令中有一大块html时,很容易出错 是的,但我想测试我所有的外部模板。有时,在使用源代码时,我会更改模板。我不想把我所有的模板都放在我的单元测试代码中,就像我当时说的,最简单的方法是直接把它们放在指令中(没有双关语)。把html和JS放在一起感觉有点糟糕,但是单元测试的好处似乎超过了其他缺点。我同意你的观点。至少我现在可以用了。我想知道如果我使用$http获取模板并将它们放在单元测试代码中的$templateCache中,一次一个模板会怎么样。。。我还没有尝试过这样的事情,但它似乎使单元测试变得更加复杂,必须处理异步问题……同时,我将接受您的答案并处理这个问题。谢谢
template: "<div>This is the template</div>"