11

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

当我运行测试时,会出现警告:

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

> 33 |   const { t } = useTranslation(['common', 'account']);
     |                 ^

我已经尝试了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');
  });

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

4

2 回答 2

5

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

jest.mock("react-i18next", () => ({
    useTranslation: () => ({ t: key => key }),
}));

希望这可以帮助。和平。

于 2021-05-25T07:52:28.293 回答
0

使用它来替换渲染功能。


import { render, screen } from '@testing-library/react'
import DarkModeToggleBtn from '../../components/layout/DarkModeToggleBtn'
import { appWithTranslation } from 'next-i18next'
import { NextRouter } from 'next/router'


jest.mock('react-i18next', () => ({
    I18nextProvider: jest.fn(),
    __esmodule: true,
 }))

  
const createProps = (locale = 'en', router: Partial<NextRouter> = {}) => ({
    pageProps: {
        _nextI18Next: {
        initialLocale: locale,
        userConfig: {
            i18n: {
            defaultLocale: 'en',
            locales: ['en', 'fr'],
            },
        },
        },
    } as any,
    router: {
        locale: locale,
        route: '/',
        ...router,
    },
} as any)

const Component = appWithTranslation(() => <DarkModeToggleBtn />)

const defaultRenderProps = createProps()

const renderComponent = (props = defaultRenderProps) => render(
    <Component {...props} />
)


describe('', () => {
    it('', () => {

        renderComponent()
     
        expect(screen.getByRole("button")).toHaveTextContent("")

    })
})


于 2022-01-11T19:51:14.320 回答