ngx-translate: Translate string in Unit Testing

12,150

Solution 1

Found a solution to translate a key in Unit Testing

First you check if your textContent equals the translate key. Then you set a translation for that key and check again if it translated:

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');
}));

Solution 2

Not sure why you would want to test this for a unit test.

The reason it doesn't work is that the translate pipe is async with the log happening while it is still retrieving the value.

I am going to assume you are already providing the TranslateModule in the TestBed.

Now, I am not sure if this will 100% work, so maybe you can give it a go. However, in theory, you can try using async and 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);
      });
    })
  );

Good luck :)!

Share:
12,150
Greg
Author by

Greg

Updated on June 09, 2022

Comments

  • Greg
    Greg almost 2 years

    I can get the value if it's a static test, but whenever I'm trying to get the translated value (using ngx-translate), it's empty.

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

    This works and returns Test

    <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);
    });
    

    Importing translate module

    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);
        }));
    

    -----FIXED----- but not sure if this is the right way to do

    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);
    });
    
  • Greg
    Greg about 6 years
    Thanks, it didn't work. However when I remove in fixture = TestBed.createComponent(NavComponent); in my code and replace it with fixture.detectChanges();.. This returns 'MENU_TITLE' still not what I want because I need the translation, but at least it's not empty anymore. Not sure if my workaround is the good way though
  • Jmsdb
    Jmsdb about 6 years
    Can I please see how you are providing the translate module? You must provide the loader so it knows where to get the translations (the same way you provide it in the app.module.ts. For more information: github.com/ngx-translate/core/issues/636
  • Greg
    Greg about 6 years
    Added in the question
  • Optimist Rohit
    Optimist Rohit over 2 years
    What will be the import for translate.setTranslation ?