2

next-i18next独自のLinkコンポーネントを使用して、ロケールのサブパスと互換性があります。

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

簡単なスナップショット テストを実行すると、エラーが発生しますCannot read property language of undefined

私のコンポーネント:

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);

これはスナップショット テストです。

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();
  });
});

Linkコンポーネントなしでテストが実行され、期待どおりに合格します。

私は自分i18n.tsを次のように定義しました:

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;

このエラーを修正できる方法はありますか?

4

1 に答える 1

1

テスト対象のコンポーネントを i18nextProvider でラップする必要があります。

Jest のスタブI18next useTranslation フックが toHaveBeenCalled をトリガーしないことを確認する

編集 I18next には、関数が常に指定されたキーを返すようにする「特別な」言語 ( cimode) がありtます。このように、テストでは、値の代わりにキーをアサートできます (開発者が変更できない場合があります)。

于 2020-09-26T04:16:31.540 に答える