如何解决如何使用next-18next设置测试环境next.js项目?当在组件测试中导入next-18next的链接失败时
设置下一个i18next - i18n.ts
const { localeSubpaths } = require('next/config').default().publicRuntimeConfig
const path = require('path')
const NextI18NextInstance = new NextI18Next({
defaultLanguage: 'en',browserLanguageDetection: true,otherLanguages: ['en','ar'],localeSubpaths,localePath: path.resolve('./public/static/locales')
})
export default NextI18NextInstance
export const {appWithTranslation,Link,Trans,Router,config,withTranslation,i18n} = NextI18NextInstance
我的组件使用next-i18next 链接组件
import React,{ FC,useState } from 'react'
import {Link} from 'i18n'
<FormGroup>
<Link href="/auth/reset-password">
<Typography className={classes.forgotPassword} variant="body2" color="primary">
{t('signIn:forgotPassword')}
</Typography>
</Link>
</FormGroup>
测试文件
import "@testing-library/jest-dom"
jest.mock('react-i18next',() => ({
useTranslation: () => ({t: (key:string):string => key})
}));
describe("Sign-in Form show",() => {
afterEach(cleanup)
it("required errors on submit empty form",async() => {
const {findByText} = render(<SignIn/>)
fireEvent.submit(await findByText('submit'))
const userError = await findByText('signIn:usernamerequired')
expect(userError).toBeInTheDocument()
const passwordError = await findByText('signIn:passwordrequired')
expect(passwordError).toBeInTheDocument()
})
如 react-i18next测试设置中所建议,我在 mocks 文件夹中模拟了react-i18n.ts
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n
.use(initReactI18next)
.init({
lng: 'en',fallbackLng: 'en',// have a common namespace used around the full app
ns: ['common','signIn'],defaultNS: 'common',debug: false,interpolation: {
escapeValue: false,// not needed for react!!
},resources: { en: { translations: {} } },});
export default i18n;
运行测试时发生错误
● Test suite Failed to run
TypeError: (0,_reactI18next.withTranslation) is not a function
> 1 | const NextI18Next = require('next-i18next').default
| ^
2 | const { localeSubpaths } = require('next/config').default().publicRuntimeConfig
3 | const path = require('path')
4 |
at Object.<anonymous> (node_modules/next-i18next/dist/commonjs/components/Link.js:132:50)
at Object.<anonymous> (node_modules/next-i18next/dist/commonjs/components/index.js:21:36)
at Object.<anonymous> (node_modules/next-i18next/dist/commonjs/hocs/app-with-translation.js:86:19)
at Object.<anonymous> (node_modules/next-i18next/dist/commonjs/hocs/index.js:19:27)
at Object.<anonymous> (node_modules/next-i18next/dist/commonjs/index.js:36:13)
at Object.<anonymous> (i18n.ts:1:21)
at Object.<anonymous> (components/sign-in-flow/SignIn.tsx:16:1)
at Object.<anonymous> (__tests__/components/SignIn.test.tsx:3:1)
作为测试的新手,我需要一种解决方案来修复所有与next-i18next相关的集成,以运行测试而不会出现任何错误。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。