如何解决来自 react-hook-forms 的 FormContext 在 testing-library-react 中导致错误
在尝试运行我的测试时,FormContext 出现一个奇怪的错误。我要做的就是渲染一个组件。
这是我得到的错误,这是我编写的测试。
import React from 'react';
import UserReportQuestion from './UserReportQuestion';
import { render } from '@testing-library/react';
import { useForm,FormContext } from 'react-hook-form';
describe('(Component) UserReport',() => {
let UserReportQuestionRender;
// jest.mock('react-hook-form',() => ({
// FormContext: jest.fn(),// useForm: jest.fn(),// }));
beforeEach(() => {
const form = useForm();
UserReportQuestionRender = render(
<FormContext {...form}>
<UserReportQuestion />
</FormContext>
)
});
it('Should render without crashing',() => {
expect(UserReportQuestionRender);
});
});
在我正在测试的组件中,我使用 FormContext 并将它 useForm 作为其方法传递。我已经注释掉了其他所有内容,因此它只是组件中的 FormContext 以确保它是 100% 导致错误的原因。
想知道是否有人对如何解决这个问题有任何想法?
使用组件更新
import { useForm,FormContext } from "react-hook-form";
const UserReportQuestion = ({ text }) => {
const { t } = useTranslation();
const [isModalOpen,setModal] = useState(false);
const methods = useForm();
return (
<>
<Question>
{t('UserReport.criteria')}:
{' '}
{/* Placeholder text */}
{/* {text} */}
Find new,creative ways of completing tasks
<ModalIcon onClick={() => setModal(true)}>
<Icon
icon="info"
color="#a3a3a3"
modifiers={['size-large','solid']}
/>
</ModalIcon>
</Question>
<InfoModal
isModalOpen={isModalOpen}
closeModal={() => setModal(false)}
title={t('UserReport.modalTitle')}
>
<FormContext {...methods}>
{/* <form onSubmit={methods.handleSubmit()}>
<InfoModalParagraph>
{t('UserReport.modalDescription')}
</InfoModalParagraph>
<FeedbackQuestions
questions={mockData}
selfAssessment={false}
submitButtonDisabled
noSubmitButton
/>
</form> */}
</FormContext>
</InfoModal>
</>
);
}
解决方法
我认为您正在导入一个不存在的组件,如果我们想使用 react-hook-form
,在 FormProvider
文档中我们有一个 useFormContext
。
在此处阅读更多相关信息:https://react-hook-form.com/api/#useFormContext
但同时你需要改变
import {FormContext} from 'react-hook-form'
为此:
import { FormProvider } from 'react-hook-form'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。