Search code examples
reactjsjestjscreate-react-appi18nextreact-i18next

'react-i18next: withNamespaces is not a function' when testing


I'm using react-i18next on a typescript project. I was using translate() HOC but it's deprecated so I've migrate to withNamespaces(). Everything used to work pretty well.

Now everything keeps working fine when I start the app, but it fails badly during the tests:

FAIL  src/containers/MainMenu/MainMenu.test.tsx
Test suite failed to run

TypeError: react_i18next_1.withNamespaces is not a function

  at Object.<anonymous> (src/components/AppMenu/AppMenu.tsx:17:35)
  at Object.<anonymous> (src/components/AppMenu/index.ts:3:17)
  at Object.<anonymous> (src/containers/MainMenu/MainMenu.tsx:18:17)
  at Object.<anonymous> (src/containers/MainMenu/MainMenu.test.tsx:42:18)
  at process._tickCallback (internal/process/next_tick.js:68:7)

Here's my AppMenu component:

My app is a pretty standard Create-React-App install.

import {TranslationFunction} from 'i18next';
import * as React from 'react';
import {withNamespaces, WithNamespaces} from 'react-i18next';
import {NavLink} from 'react-router-dom';

export interface IAppMenuProps extends WithNamespaces {
    items: IAppMenuItem[];
    t: TranslationFunction;
}

function AppMenu({items, t}: IAppMenuProps): JSX.Element {
    return (
        // ... some stuff here
    );
}

export default withNamespaces()(AppMenu);

And the test file which fails:

import * as React from 'react';
import {BrowserRouter as Router} from 'react-router-dom';
import {create} from 'react-test-renderer';
import MainMenu from './MainMenu';

describe('MainMenu', () => {
    test('Snapshot test', async () => {
        const comp = create(
            <Router>
                <MainMenu />
            </Router>
        );

        expect(comp).toMatchSnapshot();
    });
});

My app is a standard Create-React-App install, so tests are running with jest.

Can't find what I'm missing to get this working and why it's failing during tests and not at runtime.

Thanks!


Solution

  • Pretty stupid issue.. I forgot I had an auto mock file for react-i18next. So I just needed to change translate function to withNamespaces in this mock.