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:
// 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.
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
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With