Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TranslatePipe in test with Jest

I’m facing this error when I try to run test in an Angular project:

 NavigationMainComponent › should create
    TypeError: Cannot read properties of undefined (reading 'subscribe')
      at _TranslatePipe.transform (node_modules/@ngx-translate/core/dist/fesm2022/ngx-translate-core.mjs:928:75)

I tried to mock the TranslatePipe but nothing changes. I have mocked the TranslateService in this way:

{ provide: TranslateService, useValue: mock.translateServiceMock },

export const translateServiceMock = {
  addLangs: jest.fn(),
  setDefaultLang: jest.fn(),
  use: jest.fn().mockReturnValue(of('da')),
  getLangs: jest.fn().mockReturnValue(['da', 'en']),
  get: jest.fn().mockReturnValue(of('translated text')),
  instant: jest.fn((key: string) => key),
  onLangChange: of({ lang: 'en' }),
};

Also, I added TranslateModule.forRoot() to the imports.
I don’t know what is missing to make the test run properly.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

TranslatePipe internally subscribes to onTranslationChange and onDefaultLangChange. Your mock translation service does not mock those properties, so they are undefined and cause the error. You need to mock those as well.

export const translateServiceMock = {
  addLangs: jest.fn(),
  setDefaultLang: jest.fn(),
  use: jest.fn().mockReturnValue(of('da')),
  getLangs: jest.fn().mockReturnValue(['da', 'en']),
  get: jest.fn().mockReturnValue(of('translated text')),
  instant: jest.fn((key: string) => key),
  onLangChange: of({ lang: 'en' }),
  // add the following 2 lines
  onTranslationChange: of(),
  onDefaultLangChange: of(),
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading