如何才能使Reaction-I18N转换文件在使用Reaction-Testing-Library和JEST进行的单元测试中使用? [英] How can I enable react-i18n translation file to be used in the unit tests done with react-testing-library and jest?

查看:0
本文介绍了如何才能使Reaction-I18N转换文件在使用Reaction-Testing-Library和JEST进行的单元测试中使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JEST和反应测试库为我的前端应用程序进行单元测试,这是通过Reaction完成的。在我使用REACT-I18NEXT-LIBRARY添加国际化之前,我的单元测试运行良好。现在,当我运行测试时,它似乎没有找到/使用翻译文件,并且所有应该阅读的地方都留空了。我使用的是带有钩子的最新Reaction版本,而不是React。Component我使用的是这种"const-Components":

    const ComponentName = ({t}) => {
        return(
          <p>{t('example')}</p>
        )}
      export default ComponentName;

国际化在实际页面中工作得很好,但单元测试由于没有使用翻译文件而失败,所以我认为问题出在正确模拟翻译文件上。我只为使用此.ariableName类型的解决方案的较年长的Reaction找到一些建议解决方案,但这对我帮助不大。

我尝试用jest.fn()模拟它,但我不确定哪个函数是我应该模拟的函数,以及如何从测试中正确地使用useTransaction()函数。

    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);
    });
错误消息:找不到文本为:翻译文件标题的元素。这可能是因为文本由多个元素组成。在这种情况下,您可以为您的文本匹配器提供一个函数,使您的匹配器更加灵活。

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

推荐答案

最终我让模拟像这样工作(在App.js中):

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

以防有人需要。

另外,在我刚刚使用的t={key=>key}内部组件中,支持如下查询:expect(c.getByText('json.field.in.translation')).toBeDefined();

这篇关于如何才能使Reaction-I18N转换文件在使用Reaction-Testing-Library和JEST进行的单元测试中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆