首页 > 解决方案 > 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;
`;

标签: reactjsreact-testing-libraryreact-hook-form

解决方案


jest.mock('hoc/withForm', () => jest.fn(({ children }) => <form>{children}</form>));

这就是解决方案。我不得不模拟我的 HOC 以便它返回一个更基本的元素。


推荐阅读