next-i18next 单元测试错误“无法读取未定义的属性语言”与链接和玩笑

IT技术 reactjs jestjs next.js i18next next-i18next
2021-05-27 23:06:26

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;

无论如何我可以解决这个错误吗?

1个回答

您应该使用 i18nextProvider 包装您的测试组件。

在 Jest 中检查存根 I18next useTranslation 钩子不会触发 toHaveBeenCalled

编辑 I18next 有一个“特殊”语言 ( cimode),它使t函数始终返回给定的键,这样在测试中您可以对键而不是值进行断言(可以更改,有时不能由开发人员更改)。