如何使用Jest&EnzymeuseField Hook为Formik驱动的输入组件编写测试?

问题描述

TL; DR

如何使用Jest&Enzyme为带有“ useField”钩子的组件编写单元测试? 在浅色渲染中,我会收到此错误

    Warning: Formik context is undefined,please verify you are calling 
useFormikContext() as child of a <Formik> component
TypeError: Cannot read property 'getFieldProps' of undefined

详细信息

项目构建使用

  1. 反应
  2. TypeScript
  3. Formik
  4. 材料界面
  5. 开胃酵素

这是一个学习项目,所以我在尝试不同的方法。这就是为什么我认为所有组件都放在不需要的文件中的原因。

结构:

Formik.tsx
  |
  | AddContactForm.tsx
    |
    | TextInput.tsx
    | TextInput.test.tsx

详细信息:

Formik.tsx 只是一个包装,我们拥有表单的所有属性

 <Formik
            initialValues={initialValues}
            validationSchema={...}
            onSubmit={...};
            component={AddContactForm}
          />

AddContactForm.tsx 在这里,我将字段元数据和道具传递给输入。这似乎不是最佳解决方案,我想在组件本身内部使用useField()钩子

<Form>
        <TextInput
          label="First Name"
          name={"firstName"}
          placeholder="Jane"
          field={getFieldProps("firstName")}
          meta={getFieldMeta("firstName")}
        />
        <button type="submit">Submit</button>
    </Form>

TextInput.tsx 这是当前的解决方案-我可以为其编写单元测试-例如快照测试。

const TextInput: React.FC<MyInput> = React.memo(
  ({ label,field,meta}: MyInput) => {
    return (
      <>
        <TextField
          label={label}
          type="text"
          {...field}
          error={meta?.touched && meta?.error ? true : undefined}
          helperText={meta?.touched ? meta?.error : undefined}
        />
      </>
    );
  }
);

TextInput.test.tsx 在这里,我必须编写一个大的mockProps对象来模拟所有东西:(

describe("<TextInput/>",() => {
  it("Match Snapshot",() => {
    const mockProps: MyInput = {
      label: "label",name: "name",placeholder: "placeholder",meta: {
        touched: false,error: "",initialError: "",initialTouched: false,initialValue: "",value: "",},field: {
        value: "",checked: false,onChange: jest.fn(),onBlur: jest.fn(),multiple: undefined,name: "firstName",};

    expect(
      shallow(
        <TextInput
          label="label"
          name="name"
          placeholder="placeholder"
          {...mockProps.meta}
          {...mockProps.field}
        />
      )
    ).toMatchSnapshot();
  });
});

相反,我要获取的不是 field meta ,不是通过props,而是通过useField()钩子获得的。

TextField.tsx

const TextInput: React.FC<MyInput> = React.memo(
  ({ label,...props }: MyInput) => {
    const [field,meta] = useField(props);
    return (
      <>
        <TextField
          label={label}
          type="text"
          {...field}
          {...props}
          error={meta?.touched && meta?.error ? true : undefined}
          helperText={meta?.touched ? meta?.error : undefined}
        />
      </>
    );
  }
);

但是后来我不知道如何为此编写测试。似乎希望在测试中包含Formik上下文,但由于它违反了钩子用法规则,因此无法在测试文件中使用useFormikContext()钩子。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)