ngx-translate:在单元测试中翻译字符串

7

如果是静态测试,我可以获取该值,但每当我尝试获取翻译后的值(使用ngx-translate)时,它是空的。

<div id="header-title">
    <h1>{{ 'MENU_TITLE' | translate | uppercase }}</h1>
</div>

这个有效并返回测试

<div id="header-title">
    <h1>Test</h1>
</div>

spec.ts

it('should translate a string using the key value', () => {
    fixture = TestBed.createComponent(NavComponent);
    const title = fixture.nativeElement;
    console.log(title.querySelector('#header-title h1').innerHTML);
});

导入翻译模块

beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [RouterTestingModule,
                TranslateModule.forRoot({
                    loader: {
                        provide: TranslateLoader,
                        useFactory: HttpLoaderFactory,
                        deps: [HttpClient]
                    }
                }),
                HttpClientModule
            ],
            declarations: [NavComponent]
        }).compileComponents();

        injector = getTestBed();
        translate = injector.get(TranslateService);
    }));

-----已修复-----,但不确定这是否是正确的做法。

let fixture: ComponentFixture<NavComponent>;

it('should translate a string using the key value', () => {
    fixture.detectChanges() // fixture = TestBed.createComponent(NavComponent);
    const title = fixture.nativeElement;
    console.log(title.querySelector('#header-title h1').innerHTML);
});

添加完整的示例! - Carnaru Valentin
2个回答

7

在“单元测试”中找到了翻译键的解决方案。

首先,您检查您的textContent是否等于翻译键。然后为该键设置一个翻译,并再次检查是否已翻译:

it('should translate a string using the key value', async(() => {
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('#header-title h1').textContent).toEqual('MENU_TITLE');
    translate.setTranslation('en', { MENU_TITLE: 'reporting' });
    translate.use('en');
    fixture.detectChanges();
    expect(compiled.querySelector('#header-title h1').textContent).toEqual('REPORTING');
}));

translate.setTranslation 的导入将是什么? - Optimist Rohit

2

不确定为什么您想要为单元测试测试此内容。

原因是翻译管道与记录同时进行,而它仍在检索值时是异步的。

我假设您已经在TestBed中提供了TranslateModule。

现在,我不确定这是否会100%起作用,所以也许您可以尝试使用async和whenStable():

  it(
    'should translate a string using the key value',
    async(() => {
      fixture = TestBed.createComponent(NavComponent);
      const title = fixture.nativeElement;

      fixture.whenStable().then(() => {
        fixture.detectChanges();
        console.log(title.querySelector('#header-title h1').innerHTML);
      });
    })
  );

祝你好运 :)!


谢谢,它没有起作用。但是当我在我的代码中删除fixture = TestBed.createComponent(NavComponent);并替换为fixture.detectChanges();时...这仍然返回'MENU_TITLE',虽然不是我想要的翻译,但至少不再为空了。不确定我的解决方法是否正确。 - Greg
请问能否看一下您如何提供翻译模块?您必须提供加载器,以便它知道从哪里获取翻译(与在 app.module.ts 中提供的方式相同)。更多信息请参见:https://github.com/ngx-translate/core/issues/636 - Jmsdb
Added in the question - Greg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接