使用 useTranslation 进行 next-i18next Jest 测试

Phi*_*cks 5 jestjs next.js react-i18next next-i18next

测试库...总是很有趣。我next-i18next在我的 NextJS 项目中使用。我们正在使用useTranslation带有命名空间的钩子。

当我运行我的测试有一个警告:

console.warn react-i18next:: 您需要使用 initReactI18next 传入一个 i18next 实例

> 33 |   const { t } = useTranslation(['common', 'account']);
     |                 ^
Run Code Online (Sandbox Code Playgroud)

我已经尝试了react-i18next 测试示例中的设置,但没有成功。我也试过这个建议

以及只是试图嘲笑useTranslation但没有成功。

是否有更直接的解决方案来避免此警告?测试通过 FWIW...

test('feature displays error', async () => {
    const { findByTestId, findByRole } = render(
      <I18nextProvider i18n={i18n}>
        <InviteCollectEmails onSubmit={jest.fn()} />
      </I18nextProvider>,
      {
        query: {
          orgId: 666,
        },
      }
    );

    const submitBtn = await findByRole('button', {
      name: 'account:organization.invite.copyLink',
    });

    fireEvent.click(submitBtn);

    await findByTestId('loader');

    const alert = await findByRole('alert');
    within(alert).getByText('failed attempt');
  });
Run Code Online (Sandbox Code Playgroud)

最后,有没有办法让翻译的纯文本成为结果,而不是命名空间:account:account:organization.invite.copyLink

May*_*wal 16

在描述块之前或 beforeEach() 中使用以下代码片段来模拟需要的内容。

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

希望这可以帮助。和平。

  • 对我来说,它只是将它放在describe()博客之前。 (2认同)