Olg*_*lga 5 internationalization reactjs jestjs next.js react-testing-library
在我们的 Next.js 应用程序中,我们使用vinissimus/next-translate包进行翻译。我们进行相应的设置:
next.config.js:
const nextTranslate = require('next-translate')
module.exports = nextTranslate()
Run Code Online (Sandbox Code Playgroud)
i18n.js 配置文件:
{
"locales": ["en"],
"defaultLocale": "en",
"pages": {
"*": ["en"],
"/": ["en"],
}
}
Run Code Online (Sandbox Code Playgroud)
通过useTranslation钩子在组件内部使用它:
const App = () => {
const { t, lang } = useTranslation();
return (
<Homepage>
<span>{t(`${lang}:homepage.title.header`)}</span>
</Homepage>
Run Code Online (Sandbox Code Playgroud)
我的问题是如何用反应测试库来测试它?
当我在测试中渲染组件时,翻译不起作用,仅返回密钥。另外,我想通过getByText / findByText并通过来测试它:
{t(`${lang}:homepage.header`)}
Run Code Online (Sandbox Code Playgroud)
如果我在应用程序中没有使用任何i18nProvider而仅使用此i18n.js配置,如何设置某种包装器或配置进行测试?
小智 3
这是一个包装器示例:
// 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 }
Run Code Online (Sandbox Code Playgroud)
测试看起来像
// 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 />)
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1481 次 |
| 最近记录: |