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)
细节
该项目构建与
这是一个学习项目,所以我正在尝试不同的方法。这就是为什么我将所有组件放在不同的文件中,认为这可能没有必要。
结构:
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 这是当前的解决方案 - 我可以为它编写单元测试 - 例如快照测试。 …