使用useRef react钩子时如何使用玩笑来提交表单?

时间:2020-08-25 07:25:04

标签: reactjs jestjs react-hooks use-ref

我正在尝试使用笑话提交表单,但不确定如何传递字段值。我收到表格错误消息,提示必须填写字段。以下是我的组件。

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。我相信我需要模拟useRef for Form,但不确定。下面是测试,我可以单击表单,但是正如我所说,我无法通过测试调用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);
  });

});

0 个答案:

没有答案