期望:当测试一个template
或输出的directive
/应该翻译的翻译以显示实际文本component
时。<h1>{{home.title | translate}}</h1>
<h1>Home Page</h1>
现在经过大量挖掘,我已经能够通过手动将我需要的翻译放入测试中来使其工作。
示例:当前测试在测试中使用手动翻译设置,这里的关键是$translateProvider.translations
.
(function() {
'use strict';
describe('home component', function() {
var rootscope, compile, directiveElement;
beforeEach(module('Templates'));
beforeEach(module('myApp'));
beforeEach(module('tmh.dynamicLocale'), function () {
tmhDynamicLocaleProvider.localeLocationPattern('base/angular/i18n/angular-locale_{{locale}}.js');
});
beforeEach(module('pascalprecht.translate', function ($translateProvider) {
$translateProvider.translations('en', {
"home":{
"title": "Home page"
}
});
}));
beforeEach(inject(function(_$rootScope_, _$compile_) {
rootscope = _$rootScope_.$new();
compile = _$compile_;
}));
function getCompiledElement(){
var element = angular.element('<home-component></home-component');
var compiledElement = compile(element)(rootscope);
rootscope.$digest();
return compiledElement;
}
describe('home', function () {
it('should have template defined', function () {
directiveElement = getCompiledElement();
console.log('my component compiled', directiveElement);
});
});
});
})();
生成的输出是正确的:
主页
现在,上面编译了我的组件并显示正确翻译的文本,而不是看到花括号和键。现在在一个实际的应用程序中,必须手动获取所需的翻译并将其放入并不是很好,而且翻译可能会发生变化,您可能会忘记更新测试。
我希望我的测试使用实际的静态json
翻译文件
resources
| locale-en_US.json
我尝试使用下面的代码,但是由于它是异步的,它不会在测试进行时加载。我需要一种方法来等到文件加载完毕,或者以不同的方式将文件加载到$translateProvider
.
$translateProvider.useStaticFilesLoader({
prefix: 'app/resources/locale-', // path to translations files
suffix: '.json'
});
我还尝试通过karma.conf.js
如下所示加载语言 json 文件。
Files[
...
{ pattern: 'app/resources/angular-i18n/*.js', included: true, served: true },
{pattern: 'app/resources/*.json', included: true, served: true},
]
我知道必须有一种方法可以工作,但是我还没有找到解决方案。有人说他们的解决方案有效,但是我尝试使用不同的插件,但似乎仍然无法正常工作。
更新:自定义加载器
我正在阅读为$translateProvider
. 我不确定如何构建它以处理我想要的方式,以便它可以用于正确测试,但如果其他人正在研究这个,那么这可能是一个值得关注的地方。
$provide.factory('customLoader', function ($q) {
return function () {
var deferred = $q.defer();
deferred.resolve({});
return deferred.promise;
};
});
$translateProvider.useLoader('customLoader');