reactjs - 使用 useRef react hook 时如何使用 jest 提交表单?
问题描述
我正在尝试使用 jest 提交表单,但不确定如何传递字段值。我收到表单错误消息说这些字段是必需的。下面是我的组件。
export const LimitUpdate: React.FC<Props> = (props) => {
const [formKey, setFormKey] = React.useState(0);
const [description, setDescription] = React.useState("");
React.useEffect(() => {
if (props.submitSR) {
const thisForm = serlimitIncFormRef.current;
const formErrors = thisForm.triggerValidation();
if (!formErrors || Object.keys(formErrors).length === 0) {
onSubmit();
} else {
props.onSubmitComplete();
}
}
}, [props.submitSR]);
const serlimitIncFormRef = React.useRef<FormRef>();
const incrementFormKey = (): void => {
setFormKey(formKey + 1);
};
const validate = (values: FormValues): FormErrors => {
//Form Validation
};
const setLimitIncFormRef = (form: FormRef): FormRef => {
serlimitIncFormRef.current = form;
return form;
};
const internalRender = (): JSX.Element => {
<Form
testId="legacyForm"
key={formKey}
formRef={setLimitIncFormRef}
onSubmit={onSubmit}
validator={validate}
>
<ContactDetails/>
<ProblemSummary
maxLength={MAX_DESCRIPTION_LEN}
text={description}
setText={setDescription}
/>
</Form>
};
};
onSubmit() 不会被调用,因为字段值为空并且thisForm.triggerValidation()
返回 formErrors 和字段。我相信我需要模拟 Form 的 useRef,但不确定。下面是测试,我可以单击表单,但正如我所说,我无法通过测试调用 onSubmit() 方法
const props = {
onSubmitComplete: () => {},
setSev1Confirmed: () => {},
setSeverity: () => {} ,
submitSR: false,
severity: "MEDIUM" as TicketSeverityEnum,
sev1Confirmed: false,
srType: "limit" as SupportType
};
describe("create limit update support request", () => {
it("test form submission", async() => {
props.submitSR = true;
const { getByOuiTestId,debug } = render(<LimitUpdateSRCreate {...props}/>);
const form = getByOuiTestId("legacyLimitsForm");
const name = getByOuiTestId("name-id");
expect(name).toBeDefined();
fireEvent.change(name, { target: { value: "test" } });
const email = getByOuiTestId("email-id");
expect(email).toBeDefined();
fireEvent.submit(form);
});
});
解决方案
推荐阅读
- android - 如何在 Android Studio 中正确设置 Spinner
- node.js - @react-pdf/renderer 仅在第一次渲染时显示 pdf
- google-cloud-platform - BigQuery 数据传输服务 - 表名称无效
- mysql - 如何通过最新的产品交易选择行中另一个值的正确值
- abap - ABAP Dynpro Flow 逻辑 - 在 POV 调用后查找字段(名称)
- elasticsearch.net - 将 JSON 转换为有效的 ElasticSearch.NET 搜索响应对象以进行模拟
- wordpress - 如何更改 WP Cron 间隔?
- django - 类型错误:create_user() 缺少 1 个必需的位置参数:“密码”
- jquery - 添加新行后刷新引导表
- python - 如何使用python在字符串中间插入一个或多个字符?