I\'m trying to stub/spy the translation, not just mock it, and I can\'t seem to get it to trigger even in this most base case.
2 Things that you should improve in your code:
useTransaltion
is a hook which requires context
, make sure you wrap you component with i18nextProvider
.shallow
with mount
.i18next
has a built-it support of tests.
In order to enable it use cimode as the lng
when configuring your i18next
for tests.// i18nForTests.js
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n.use(initReactI18next).init({
lng: 'cimode',
// ----- ^
// have a common namespace used around the full app
ns: ['translations'],
defaultNS: 'translations',
interpolation: {
escapeValue: false, // not needed for react!!
},
resources: { en: { translations: {} } },
});
export default i18n;
// SomeComponent.test.js
import { mount } from 'enzyme';
import { I18nextProvider } from 'react-i18next';
import i18n from '../i18nForTests';
describe('<SomeComponent />', () => {
it('dispatches SORT_TABLE', () => {
const enzymeWrapper = mount(
<I18nextProvider i18n={i18n}>
<SomeComponent />
</I18nextProvider>
);
enzymeWrapper.find('.sort').simulate('click');
expect(enzymeWrapper.find('#some-text').text()).toEqual('MY_TRANS_KEY');
});
});
Edit: Version with mocked I18next
// i18nextMock.js
export const i18nextMock = {
t: jest.fn(),
// Do the same for other i18next fields
};
// SomeComponent.test.js
import { mount } from 'enzyme';
import { I18nextProvider } from 'react-i18next';
import i18nextMock from '../i18nextMock';
describe('<SomeComponent />', () => {
it('dispatches SORT_TABLE', () => {
const enzymeWrapper = mount(
<I18nextProvider i18n={i18nextMock}>
<SomeComponent />
</I18nextProvider>
);
enzymeWrapper.find('.sort').simulate('click');
expect(enzymeWrapper.find('#some-text').text()).toEqual('MY_TRANS_KEY');
});
});