Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngx-translate how to test components

I've got an application which uses this library. How do I test components with it? I DO NOT WANT TO TEST THE LIBRARY. I just need to start tests of my component without multiple errors about TranslateModule then TranslateService then TranslateStore ... until I get an error when compiling.

Is there an easy way to just run my tests with this dependency?

Once more, I don't want to test this library (check whether the string is being translated) I need to run tests on components which rely on this library.

like image 357
Sergey Avatar asked Nov 19 '18 08:11

Sergey


People also ask

How does Ngx-translate work?

NGX-Translate is an internationalization library for Angular. It lets you define translations for your content in different languages and switch between them easily. Check out the demo on StackBlitz. It gives you access to a service, a directive and a pipe to handle any dynamic or static content.

What is NGX testing?

Check out a sample report. Your NGX report will help you discover how to unlock new levels of fitness, health and wellbeing. It includes your DNA results, personalised nutrition recommendations, carbohydrate and fat sensitivity, gluten and lactose tolerance, vitamin needs and much, much more.

How is testing done in Angular?

To run the test, you will only need to run the command ng test . This command will also open Chrome and run the test in watch mode, which means your test will get automatically compiled whenever you save your file. In your Angular project, you create a component with the command ng generate component doctor .


2 Answers

If you don't necessarily need the keys to be translated you can import the TranslateModule in your test like this:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [
      ...
    ],
    imports: [
      TranslateModule.forRoot(),
    ],
    providers: [
      ...
    ]
  })
  .compileComponents();
}));

It will only show the translation keys

like image 175
Chantal Avatar answered Oct 01 '22 06:10

Chantal


For me the ngx-translate-testing worked well https://www.npmjs.com/package/ngx-translate-testing

first

import { TranslateTestingModule } from 'ngx-translate-testing';

then

  imports: [
    ...
    TranslateTestingModule.withTranslations({ en: require('src/assets/i18n/en.json'), de: require('src/assets/i18n/de.json') })
  ], 

then test

  it('should render german title', inject([TranslateService], (translateService: TranslateService) => {
    translateService.setDefaultLang('de');
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('.title').textContent).toContain('GERMANTITLE');
  }));
like image 24
wutzebaer Avatar answered Oct 01 '22 04:10

wutzebaer