next-i18next unit testing error 'Cannot read property language of undefined' with Link and jest

5.7k views Asked by At

next-i18next uses it's own Link component to be compatible with locale sub-paths.

https://github.com/isaachinman/next-i18next

When I try a simple snapshot test I get the error Cannot read property language of undefined.

My component:

import React from 'react';
import { TFunction } from 'next-i18next';
import { withTranslation, Link } from '../../../i18n';

interface HeaderProps {
  readonly t: TFunction;
}

const Header = ({ t }: HeaderProps): JSX.Element => {
  return (
    <>
      <Flex>
        <Box>
          <Link href="/">{t('home')}</Link>
        </Box>
      </Flex>
    </>
  );
};

export default withTranslation('common')(Header);

It's snapshot test:

import React from 'react';
import { render, screen } from '@testing-library/react';
import Header from './Header';

describe('<Header/>', () => {
  test('it should render correctly', () => {
    const { container } = render(<Header />);
    expect(container.firstChild).toMatchSnapshot();
  });
});

The test runs and passes without the Link component as expected.

I have defined my i18n.ts as follows:

import path from 'path';
import NextI18Next from 'next-i18next';
import { publicRuntimeConfig } from './next.config';

const { localeSubpaths } = publicRuntimeConfig;

export const nextI18next = new NextI18Next({
  browserLanguageDetection: false,
  defaultNS: 'common',
  defaultLanguage: 'en',
  fallbackLng: 'en',
  otherLanguages: ['fr'],
  localeSubpaths,
  localePath: path.resolve('./public/static/locales'),
});

export const {
  i18n,
  appWithTranslation,
  Link,
  withTranslation,
  Router,
} = nextI18next;

Is there anyway I can fix this error?

2

There are 2 answers

9
felixmosh On

You should wrap your component under test with i18nextProvider.

Check Stubbing I18next useTranslation hook in Jest doesn't trigger toHaveBeenCalled

Edit I18next has a "special" languages (cimode) which makes the t function always return the given key, this way in tests you can assert on the key instead of the value (which can be changed, sometimes not by the developer).

0
nDiviD On

For every one who can't get why this error is exist: check your locale files is correct and doesn't content special symbols out of quotes