angularts-jestngx-translateangular-unit-test

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.


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