小编Myk*_*rat的帖子

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

TL; 博士

如何使用 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
Run Code Online (Sandbox Code Playgroud)

细节

该项目构建与

  1. 反应
  2. 打字稿
  3. 福米克
  4. 材质界面
  5. 玩笑酵素

这是一个学习项目,所以我正在尝试不同的方法。这就是为什么我将所有组件放在不同的文件中,认为这可能没有必要。

结构:

Formik.tsx
  |
  | AddContactForm.tsx
    |
    | TextInput.tsx
    | TextInput.test.tsx
Run Code Online (Sandbox Code Playgroud)

细节:

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

 <Formik
            initialValues={initialValues}
            validationSchema={...}
            onSubmit={...};
            component={AddContactForm}
          />
Run Code Online (Sandbox Code Playgroud)

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

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

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

unit-testing reactjs jestjs enzyme formik

10
推荐指数
1
解决办法
3275
查看次数

标签 统计

enzyme ×1

formik ×1

jestjs ×1

reactjs ×1

unit-testing ×1