用于测试角度的 Transloco 加载器模块...无法以编程方式导入翻译?

问题描述 投票:0回答:1

Transloco 有点新,但我让这个模块可以用来测试我的组件:


import { TranslocoTestingModule, TranslocoTestingOptions } from '@jsverse/transloco';
import { SUPPORTED_LANGUAGES } from './constants'; // ['en', 'es', 'de', 'fr', 'zh-CN', 'zh-TW'];

// TODO find a way to programmatically import languages from SUPPORTED_LANGUAGES
// (may not be possible with TranslocoTestingModule or with the variable pattern below)
import en from '../../assets/i18n/en.json';
import es from '../../assets/i18n/es.json';
import de from '../../assets/i18n/de.json';
import fr from '../../assets/i18n/fr.json';
import zhCN from '../../assets/i18n/zh-CN.json';
import zhTW from '../../assets/i18n/zh-TW.json';

export function getTranslocoModule(options: TranslocoTestingOptions = {}) {
  return TranslocoTestingModule.forRoot({
    langs: {
      en,
      es,
      de,
      fr,
      'zh-CN': zhCN,
      'zh-TW': zhTW,
    },
    translocoConfig: {
      availableLangs: SUPPORTED_LANGUAGES,
      defaultLang: 'en',
    },
    preloadLangs: true,
    ...options
  });
}

我愿意按照 TODO 所说的去做;不要过度声明语言,从而使模块枯竭。也就是说,使用 SUPPORTED_LANGUAGES const 来填充 langs 属性。

我尝试执行类似的操作来构建路径对象,然后在运行时获取翻译文件:

const generateLanguagePaths = (languages: readonly string[]) => {
  const basePath = '../../assets/i18n/';
  return languages.reduce((paths, lang) => {
    paths[lang] = `${basePath}${lang}.json`;
    return paths;
  }, {} as Record<string, string>);
};

const LANGUAGE_PATHS = generateLanguagePaths(SUPPORTED_LANGUAGES);

但我必须迭代生成的对象,然后解决加载文件的承诺。同时,规范文件将决定它不等待所有这些,并且它会退出并抛出错误。

有没有办法修改此规范以等待异步导入?也许是用

then
定义模块来配置测试台的某种承诺?

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ExampleOneComponent } from './example-one.component';
import { getTranslocoModule } from 'src/app/helpers/transloco-testing.module';

describe('ExampleOneComponent', () => {
  let component: ExampleOneComponent;
  let fixture: ComponentFixture<ExampleOneComponent>;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        ExampleOneComponent,
        getTranslocoModule(),
      ],
    });
    fixture = TestBed.createComponent(ExampleOneComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
angular jasmine karma-jasmine translation transloco
1个回答
0
投票

您是否能够将 transloco 配置对象声明为常量,而不是在调用

TranslocoTestingModule.forRoot()
时声明内联并在执行测试之前等待承诺?

© www.soinside.com 2019 - 2024. All rights reserved.