Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock i18Next with Jest

I spent the entire day looking at this issue, trying different solutions, but nothing seems to work.

Here's a summary of my code:

// lib/i18next.ts
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

... (i18next initialization boilerplate)

export default i18n;
export const t = (str, options?) => i18n.t(str, options);

Then in the file where the test is failing:

import { t } from '../lib/i18next';

export function thingToTranslate() {
  t('key_1', { color: red }), // where key1 can be 'The house color is ' 
}

In the tests I have the following:

// several imports

describe('my test', () => {
  it('does something', () ={
    expect(thingToTranslate()).toEqual('The house color is red');
  })
}

The above code fails with the test:

Expected: "The house color is red"
Received: "key_1"

Things I tried so far:

  • Mocking
// several imports

jest.mock('i18next', () => ({
  use: () => this,
  init: () => { },
  t: k => k
}));

describe('my test', () => {
  it('does something', () ={
    expect(thingToTranslate()).toEqual('The house color is red');
  })
}

results in TypeError: Cannot read property 'init' of undefined. I tried several variations of the above. Either it returns the previous error (Received: "key_1") or it returns the above.

  • Config file

I also tried adding this file to my __mocks__ directory (from the react-i18next docs) and variations I found online

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

i18n
  .use(initReactI18next)
  .init({
    lng: 'en',
    fallbackLng: 'en',

    // have a common namespace used around the full app
    ns: ['translations'],
    defaultNS: 'translations',

    debug: true,

    interpolation: {
      escapeValue: false, // not needed for react!!
    },

    resources: { en: { translations: {} } },
  });

export default i18n;

but this yields

You are passing an undefined module! Please check the object you are passing to i18next.use()

      ## | };
      ## |
    > ## | i18n.use(initReactI18next).init({

I am aware of similar posts that seem to work, but as I mentioned here, it's not working for me, but don't know what's wrong

like image 246
XueXu Avatar asked Oct 20 '25 09:10

XueXu


1 Answers

Instead of mocking the entire lib, you can pass cimode as lng which will make the t function to return the key itself.

All you need to do is in your tests call the changeLanguage.

i18next
  .changeLanguage('cimode')
like image 84
felixmosh Avatar answered Oct 21 '25 23:10

felixmosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!