Valentina Maronese
Valentina Maronese

Reputation: 43

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.

Upvotes: 1

Views: 82

Answers (1)

JSON Derulo
JSON Derulo

Reputation: 17467

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

Upvotes: 1

Related Questions