gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:40:25 24 4
gpt4 key购买 nike

TL;DR
如何使用 Jest & Enzyme 为带有“useField”钩子(Hook)的组件编写单元测试?
在浅渲染我得到这个错误

    Warning: Formik context is undefined, please verify you are calling 
useFormikContext() as child of a <Formik> component
TypeError: Cannot read property 'getFieldProps' of undefined
详情
该项目构建与
  • react
  • typescript
  • 福米克
  • Material 界面
  • Jest enzyme

  • 这是一个学习项目,所以我正在尝试不同的方法。这就是为什么我将所有组件放在不同的文件中,认为这可能没有必要。
    结构:
    Formik.tsx
    |
    | AddContactForm.tsx
    |
    | TextInput.tsx
    | TextInput.test.tsx
    详情:
    Formik.tsx
    只是一个包装器,我们拥有表单的所有属性
     <Formik
    initialValues={initialValues}
    validationSchema={...}
    onSubmit={...};
    component={AddContactForm}
    />
    AddContactForm.tsx
    在这里,我将字段元和 Prop 传递给输入。这似乎不是最好的解决方案,我想在组件本身内部使用 useField() 钩子(Hook)
    <Form>
    <TextInput
    label="First Name"
    name={"firstName"}
    placeholder="Jane"
    field={getFieldProps("firstName")}
    meta={getFieldMeta("firstName")}
    />
    <button type="submit">Submit</button>
    </Form>
    文本输入.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}
    />
    </>
    );
    }
    );
    文本输入.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();
    });
    });
    相反,我想要的不是通过 Prop ,而是通过 useField() 钩子(Hook)来获取字段和元数据。
    文本字段.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() 钩子(Hook),因为它违反了钩子(Hook)使用规则。

    最佳答案

    要了解有关 Mocking in Jest 的更多信息,您应该阅读以下官方文档:

  • ES6 Class Mocks
  • Mock Functions
  • Manual Mocks

  • 也可以看 Enzyme's ShallowWrapper API documentation
    // TextInput.test.tsx
    import React from 'react';
    import { useField } from 'formik'; // package will be auto mocked
    import TextInput from '...';

    jest.mock('formik'); // formik package is auto mocked

    describe("<TextInput/>", () => {
    it("Match Snapshot", () => {
    const mockMeta = {
    touched: false,
    error: "",
    initialError: "",
    initialTouched: false,
    initialValue: "",
    value: "",
    }
    const mockField = {
    value: "",
    checked: false,
    onChange: jest.fn(),
    onBlur: jest.fn(),
    multiple: undefined,
    name: "firstName",
    };
    useField.mockReturnValue([mockField, mockMeta]);

    const mockProps = {...};
    expect(
    shallow(<TextInput {...mockProps} />).debug()
    ).toMatchSnapshot();
    });
    });
    // TextInput.tsx
    import React from 'react';
    import { useField } from 'formik';
    import ...

    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}
    />
    </>
    );
    }
    );

    关于reactjs - 如何使用 Jest 和 Enzyme(useField Hook)为 Formik 驱动的输入组件编写测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63612809/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com