reactjs - React 测试库 - 渲染没有显示所有的孩子
问题描述
尝试为我的 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;
`;
解决方案
jest.mock('hoc/withForm', () => jest.fn(({ children }) => <form>{children}</form>));
这就是解决方案。我不得不模拟我的 HOC 以便它返回一个更基本的元素。
推荐阅读
- python - 在 python 中限制对 API 的请求
- python - 如何在 DataFrame 列类型的对象中找到唯一值?
- reactjs - 将卡数据发送到 onswiped 功能
- amazon-web-services - 使用 AWS Lambda 对 Hasura 身份验证挂钩的空响应
- r - R用来自交替向量的输入填充多维数组
- asp.net-mvc - 我如何在 asp.net mvc 中使用数据库首先使用现有数据库实现 asp.net,我正在使用 mac os
- python - 为什么这两个回溯算法具有相同的输出?
- php - php jwt 令牌身份验证未能通过苹果商店连接 api
- javascript - 在 Ajax 调用后触发 jQuery - 插件 Ajax 分层导航 - WooCommerce
- c# - WPF Xaml 建议不适用于 VS2019 16.4.4