React 测试库 - i18n 翻译不起作用

nic*_*ick 7 javascript reactjs

我正在尝试测试一个组件,这是简化的组件:

const Block = () => {
   const { t } = useTranslation();
  
   return <p data-testid="text">{t('some.text')}</p>;
}
Run Code Online (Sandbox Code Playgroud)

然后我有这个测试:

test('That the text is correct', () => {
  const wrapper = render(
    <I18nextProvider i18n={i18n}>
      <Block />
    </I18nextProvider>
  );

  expect(wrapper.getByTestId('text')).toHaveTextContent('Hello!');
});
Run Code Online (Sandbox Code Playgroud)

i18n 是我的配置文件,如下所示:

i18n
  .use(Backend)
  .use(initReactI18next)
  .init({
    fallbackLng: 'en',
    lng: 'en'
    debug: false,
    react: {
      useSuspense: false,
    },
    interpolation: {
      escapeValue: false,
    },
  });
Run Code Online (Sandbox Code Playgroud)

但我仍然得到:

Expect element to have text content:
   Hello!
Received:
   some.text
Run Code Online (Sandbox Code Playgroud)

我怀疑是后端插件导致它无法工作。

Nat*_*ova 2

我简单地通过在我的测试中导入 i18n 配置文件解决了这个问题。

首先我尝试了文档,但仍然会得到相同的错误。最后,经过一些修复后,我的测试工作正常,看起来像这样:

import {render, screen} from '@testing-library/react'
import myComponent from "path/to/MyComponent";
import "path/to/i18n";

describe('MyComponent', () => {
  it('should render input with placeholder', () => {
      render(<MyComponent/>);
      const placeholderItem = screen.getByPlaceholderText('translation');
      expect(placeholderItem).toBeInTheDocument();
  })
}
Run Code Online (Sandbox Code Playgroud)

组件如下所示:

import * as React from 'react';
import {useTranslation} from 'react-i18next';

export default function MyComponent() {
    const {t} = useTranslation();

    return (<Input placeholder={t("key") ?? ''}/>);
}

Run Code Online (Sandbox Code Playgroud)

所以,对我来说改变游戏规则的是在我的测试中导入 "path/to/i18n" i18n 配置文件