【问题标题】:How to mock the elements of react-hook-form when testing with react-testing-library?使用 react-testing-library 进行测试时如何模拟 react-hook-form 的元素?
【发布时间】:2022-01-23 06:52:40
【问题描述】:

拥有一个使用 react-hook-form 的基本组件:

const { handleSubmit, 重置, 控制 } = useForm({ 解析器:yupResolver(schema) });

...

  <MyComponent
    title='title'
    open={isOpened}
    control={control}
  />

这个组件有 3 个 props,title - 一个字符串,open - 一个函数,control - 不知道是什么,都是必填项。

因此,在为它编写测试时,我陷入了困境:

import { render } from '@testing-library/react';

import '@testing-library/jest-dom';
import MyComponent from './my-component';

describe('MyComponent', () => {
  const title = 'title';
  it('should render successfully', () => {
    const { baseElement, getByText } = render(
      <TaskModal
        title={title}
        open={jest.fn()}
        control={} // what should be written here?
      />
    );
    expect(baseElement).toBeTruthy();
    expect(getByText(title)).toBeTruthy();
  });

control 怎么能被这个测试模拟?

【问题讨论】:

  • control 来自哪里?您至少应该提供控制变量在何处定义或从哪个模块导入

标签: javascript reactjs typescript react-testing-library react-hook-form


【解决方案1】:

control 来自useForm

const { control } = useForm();

使用ControlleruseController 时需要控制 文档:https://react-hook-form.com/api/usecontroller

我想TaskModal 组件在一个表单中。我建议将表单放在 modal 中,这样会更容易测试,否则您可以使用表单包装您的组件(TaskModal)以进行测试。

【讨论】:

猜你喜欢
  • 2019-10-30
  • 2020-05-09
  • 2019-08-29
  • 1970-01-01
  • 2019-05-21
  • 1970-01-01
  • 2021-11-30
  • 2019-11-11
  • 2021-02-11
相关资源
最近更新 更多