使用react-testing-library进行测试时如何模拟react-hook-form的元素?

Leo*_*ssi 5 javascript typescript reactjs react-testing-library react-hook-form

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

const { 处理提交、重置、控制 } = useForm({ 解析器: yupResolver(schema) });

...

  <MyComponent
    title='title'
    open={isOpened}
    control={control}
  />
Run Code Online (Sandbox Code Playgroud)

这个组件有 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();
  });
Run Code Online (Sandbox Code Playgroud)

control这个测试怎么能被嘲笑呢?

Jor*_*ris 0

control来自useForm

const { control } = useForm();

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

我想该TaskModal组件是一种形式。我建议将表单放在模态中,这样测试会更容易,否则您可以用表单包装组件(TaskModal)进行测试。