如何在使用 react-testing-library 和 jest 完成的单元测试中启用 react-i18n 翻译文件?

Son*_*ila 16 internationalization i18next reactjs jestjs react-testing-library

我正在使用 jest 和 react-testing-library 为我使用 React 完成的前端应用程序进行单元测试。在我使用 react-i18next -library 添加国际化之前,我的单元测试运行良好。现在,当我运行测试时,它似乎没有找到/使用翻译文件,并且所有应该读取内容的地方都留空。我使用的是带有钩子的最新 React 版本,而不是 React.Component 我使用的是这种“const-components”:

    const ComponentName = ({t}) => {
        return(
          <p>{t('example')}</p>
        )}
      export default ComponentName;
Run Code Online (Sandbox Code Playgroud)

国际化在实际页面中完美运行,但由于未使用翻译文件而导致单元测试失败,所以我认为问题在于正确模拟翻译文件。我只是使用 this.variableName 类型的解决方案为较旧的反应找到一些建议解决方案,但这对我没有多大帮助。

我试图用 jest.fn() 模拟它,但我不确定哪个函数是那个,我应该模拟哪个函数以及如何从测试中正确利用 useTranslation() 函数。

    import React from 'react';
    import { useTranslation, Trans } from 'react-i18next';
    import { render } from '@testing-library/react';
    import ComponentName from './ComponentName';

    import '../locales/i18n';

    test('renders all documents in the list', () => {
      const mockUseTranslation = jest.fn();

      const { t, i18n } = mockUseTranslation();

      // const t = jest.fn();
      const c = render(<ComponentName t={t} />);
      expect(c.getByText('Translation File Title')).toBeDefined();
      expect(
        c.getAllByText(
          'Lorem ipsum'
        ).length
      ).toBe(3);
    });
Run Code Online (Sandbox Code Playgroud)

错误消息:无法找到带有文本的元素:翻译文件标题。这可能是因为文本被多个元素分解了。在这种情况下,您可以为您的文本匹配器提供一个功能,使您的匹配器更加灵活。

简而言之:应该包含某些文本的地方现在完全是空的。

onu*_*tan 10

例如,您不应该模拟翻译,而是将带有翻译库的组件渲染为高阶组件;

import React from 'react';
import i18n from '../../../i18n' // your i18n config file
import { render } from '@testing-library/react';
import ComponentName from './ComponentName';
import { I18nextProvider } from 'react-i18next'

test('renders all documents in the list', () => {
    const c = render(
      <I18nextProvider i18n={i18n}> // actually give translation to your component
         <ComponentName />
      </I18nextProvider>
    );
    // example if you have a key called example
    expect(c.getByText(i18n.getDataByLanguage('en').translation.example)).toBeDefined(); 
});
Run Code Online (Sandbox Code Playgroud)

您可以提供项目的默认翻译,而不是使用 i18n.getDataByLanguage('en') 调用您的翻译文本,如果它是法语,请通过 i18n.getDataByLanguage('fr') 调用它。

也像这样改变你的组件,而不是从 props 中获取 useTranslation 钩子,把它带入带有钩子的组件中

组件名称.jsx

import { useTranslation } from 'react-i18next'

const ComponentName = () => {
  const { t } = useTranslation()

  return(
    <p>{t('example')}</p>
  )}

export default ComponentName;
Run Code Online (Sandbox Code Playgroud)

  • 我不知道该对你说什么,但非常感谢你,因为我一整天都坐在这个问题上&lt;3:)! (2认同)

Son*_*ila 7

最终我得到了这样的模拟(在 App.js 中):

jest.mock('react-i18next', () => ({
  useTranslation: () => ({
    t: key => key,
    i18n: { changeLanguage: jest.fn() }
  })
}));
Run Code Online (Sandbox Code Playgroud)

万一有人需要这个。

另外在我刚刚使用的组件内部t={key=>key},它启用了这样的查询:expect(c.getByText('json.field.in.translation')).toBeDefined();

  • 您无法使用这种方法测试“{{count}} books”之类的值 (2认同)