Search code examples
angulartypescriptjasminengx-translate

Unable to test component that uses translation pipe (The pipe 'translate' could not be found)


I have a component that uses ngx-translate for localization. The basic unit test to create the module does not work. It fails with the following error:

PatientDataComponent should create FAILED
   [ERROR ->]{{ 'patient.information' | translate }}
  </p>
  The pipe 'translate' could not be found ("<p>[ERROR ->]{{ 'patient.information' | translate }}</p>"): ng:///DynamicTestModule/PatientDataComponent.html@1:2
error properties: Object({ ngSyntaxError: true, ngParseErrors: [ The pipe 'translate' could not be found ("<p>"): ng:///DynamicTestModule/PatientDataComponent.html@1:2 ] })

The application is able to switch languages; thus ngx-translate seems to work. Except in my unit test. The test code looks as follows:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { PatientDataComponent } from './patient-data.component';

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [PatientDataComponent]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(PatientDataComponent);
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

What do I need to do to resolve this error and make the component testable?


Solution

  • in your testBed config add in imports the TranslateModule like you do in your appModule or the module where the component is declared. for example:

    TestBed.configureTestingModule({
      declarations: [PatientDataComponent],
      imports: [
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useFactory: I18nHttpLoaderFactory,
            deps: [HttpClient],
          },
        }),
      ],
    }).compileComponents();
    

    Maybe you have other translation config.