如何正确模拟i18next

问题描述

这是我的功能和测试的简化版本。尽管我嘲笑useTranslation,但出现以下错误

您正在传递未定义的模块!请检查您的对象 传递给i18next.use()

   7 | i18n
   8 |   .use(Backend)
>  9 |   .use(initReactI18next)

如何正确模拟以摆脱此错误

import React from 'react'
import { useTranslation } from 'react-i18next'
import * as Constants from 'constants'
import MyComponent from 'components'

const Dashboard = () => {
  const { t } = useTranslation('dashboard')
  return (
     <div> Dashboard 
      <MyComponent name={t(Constants.MYCOMPONENT)}/>
    </div>
  )
}

export default Dashboard
jest.mock('react-i18next',() => ({
  useTranslation: () => ({ t: (key) => key })
}))
it('Render Dashboard without crash',() => {
  const div = document.createElement('div')
  ReactDOM.render(<Dashboard/>,div)

})

解决方法

我能让它为我们的设置工作的唯一方法如下:

jest.mock("react-i18next",() => ({
    initReactI18next: { type: "3rdParty",init: jest.fn() },useTranslation: () => ({ t: (key: string) => key }),Trans: ({ children }: { children: React.ReactNode }) => children,}));

initReactI18next: { type: "3rdParty",

作为拼图的最后一块,参考 here

,

无需模拟i18next,此库支持cimode,它将始终返回传递的密钥。

要启用它,您要做的就是在配置中以cimode的形式传递lang