【问题标题】:next-i18next unit testing error 'Cannot read property language of undefined' with Link and jestnext-i18next 单元测试错误“无法读取未定义的属性语言”,带有链接和玩笑
【发布时间】:2023-06-23 17:02:01
【问题描述】:

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;

有没有办法解决这个错误?

【问题讨论】:

  • 你知道@RyanP13 了吗?

标签: reactjs jestjs next.js i18next next-i18next


【解决方案1】:

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

查看Stubbing I18next useTranslation hook in Jest doesn't trigger toHaveBeenCalled

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

【讨论】:

  • 这对我没有帮助。你能分享更多关于这个language属性的信息吗?
  • 如果重要的话,我在 Next.js 9.5.4 上。
  • 是的,“TypeError:无法读取未定义的属性‘语言’”当页面组件和常规 React 组件具有从 i18n 导入的链接时,它会显示它们。如果链接被注释掉也没问题,测试可以识别视图中使用的其他翻译键。我将不胜感激有关下一步调试的一些提示。
  • 您是否使用 i18nextProvider 包装了您的被测组件?
  • 我使用了自定义渲染函数 (testing-library.com/docs/…),尝试了 I18NextProvider(locale 未作为 prop 传递)和 IntlProvider(传递 locale='en'),结果相同。
最近更新 更多