首页 > 解决方案 > 使用 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);
  });

});

标签: reactjsjestjsreact-hooksuse-ref

解决方案


推荐阅读