[英]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.