我正在使用 jest 和 react-testing-library 为我使用 React 完成的前端应用程序进行单元测试。在我使用 react-i18next -library 添加国际化之前,我的单元测试运行良好。现在,当我运行测试时,它似乎没有找到/使用翻译文件,并且所有应该读取内容的地方都留空。我使用的是带有钩子的最新 React 版本,而不是 React.Component 我使用的是这种“const-components”:
const ComponentName = ({t}) => {
return(
<p>{t('example')}</p>
)}
export default ComponentName;
Run Code Online (Sandbox Code Playgroud)
国际化在实际页面中完美运行,但由于未使用翻译文件而导致单元测试失败,所以我认为问题在于正确模拟翻译文件。我只是使用 this.variableName 类型的解决方案为较旧的反应找到一些建议解决方案,但这对我没有多大帮助。
我试图用 jest.fn() 模拟它,但我不确定哪个函数是那个,我应该模拟哪个函数以及如何从测试中正确利用 useTranslation() 函数。
import React from 'react';
import { useTranslation, Trans } from 'react-i18next';
import { render } from '@testing-library/react';
import ComponentName from './ComponentName';
import '../locales/i18n';
test('renders all documents in the list', () => {
const mockUseTranslation = jest.fn();
const { t, i18n } = mockUseTranslation();
// const t …Run Code Online (Sandbox Code Playgroud) internationalization i18next reactjs jestjs react-testing-library