【发布时间】:2021-01-19 09:39:43
【问题描述】:
尝试为我的 react-hook-form 编写一个测试,以便检查它是否正确呈现。目前我在第一关失败了,无法让我的表单呈现它的孩子:
const props = {
request: true,
title: "testing title",
commentPlaceholder: "Placeholder",
tip: "helpful tip",
submitButtonText: "submit",
onSubmit: jest.fn(),
recipientName: "User one",
activeStep: 2,
};
it('Should render the CommentForm as if it was in the request flow', async () => {
const { getByText, getByTestId, debug } = render(
<CommentForm {...props} />
);
console.log(debug());
});
控制台日志输出如下:
<body>
<div>
<form />
</div>
</body>
我正在测试的组件中有很多子组件来创建表单。
我已将其指向我在组件中使用的包装器。
<StyledForm onSubmit={onSubmit} schema={CommentSchema} onChange={handleChange}>
如果我将其更改为表单,那么它将呈现我所有的孩子。这是一个样式化的组件,它在下面扩展了这个方法:
const Form = ({ className, onSubmit, schema, defaultValues, children, mode, onChange, style }) => {
const methods = useForm({
defaultValues,
validationSchema: schema,
validateCriteriaMode: 'all',
mode: mode || 'onSubmit',
});
const { handleSubmit, watch } = methods;
const values = watch();
useEffect(() => {
onChange && onChange(values);
}, [onChange, values]);
return (
<FormContext {...methods}>
<form style={style} className={className} onSubmit={handleSubmit(onSubmit)}>
{children}
</form>
</FormContext>
);
};
我知道这是导致问题的原因,但我不明白为什么它不会渲染组件。这也是为什么当我将StyledForm 更改为普通的form 元素时它可以工作的原因。
** 更新 **
现在发现这似乎是因为我正在像这样扩展 styledComponent:
export const StyledForm = styled(Form)`
width: 100%;
margin: 0 auto 50px;
`;
【问题讨论】:
标签: reactjs react-testing-library react-hook-form