【问题标题】:Testing components using next-translate and i18n使用 next-translate 和 i18n 测试组件
【发布时间】:2021-06-26 07:34:10
【问题描述】:

在我们的 Next.js 应用程序中,我们使用 vinissimus/next-translate 包进行翻译。 我们进行了相应的设置:

next.config.js

const nextTranslate = require('next-translate')
module.exports = nextTranslate()

i18n.js 配置文件

{
  "locales": ["en"],
  "defaultLocale": "en",
  "pages": {
    "*": ["en"],
    "/": ["en"],
  }
}

通过 useTranslation 钩子在组件内使用它:

const App = () => {
  const { t, lang } = useTranslation();

  return (
    <Homepage>
          <span>{t(`${lang}:homepage.title.header`)}</span>
    </Homepage>

我的问题是如何用 react-testing-library 开玩笑地测试它?

当我在测试中渲染我的组件时,翻译不起作用,只返回键。另外,我想通过 getByText / findByText 测试它并通过:

{t(`${lang}:homepage.header`)}

如果我没有在应用程序中使用任何 i18nProvider 而只使用这个 i18n.js 配置,我该如何设置某种包装器或配置来进行测试? p>

【问题讨论】:

    标签: reactjs jestjs next.js internationalization react-testing-library


    【解决方案1】:

    这是一个示例包装器:

    // tests/wrapper.js
    import { render } from '@testing-library/react'
    import I18nProvider from 'next-translate/I18nProvider'
    
    import commonEN from '../locales/en/common.json'
    
    const Providers = ({ children }) => (
      <I18nProvider
        lang={'en'}
        namespaces={{
          common: commonEN
        }}
      >
        {children}
      </I18nProvider>
    )
    
    const customRender = (ui, options = {}) => render(ui, { wrapper: Providers, ...options })
    
    export * from '@testing-library/react'
    
    export { customRender as render }
    

    测试看起来像

    // App.spec.js
    import React from 'react'
    import { render } from './tests/wrapper'
    import App from './App'
    
    jest.mock('next/router', () => ({
      useRouter() {
        return {
          asPath: '/'
        }
      }
    }))
    
    describe('App', () => {
      it('should render the app', async () => {
        const res = render(<App />)
      })
    })
    

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 2020-10-16
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多