react-hook-form V7:如何使用 jet 对 MUI 组件进行单元测试?

react-hook-form V7: how unit test a MUI component with jets?

我有以下组件将 control 作为参数:

const TexInputMUI = (props) => {
  const { control, variant, margin, ...rest } = props
  return (
    <Controller
      name='myMUItf'
      defaultValue=''
      control={control}
      render={({ field }) => (
        <TextField
          {...field}
          variant={variant}
          margin={margin}
          label='A simple MIU text field'
          {...rest}
        />
      )}
    />
  )
}

而且,我有一个简单的测试想检查组件是否渲染

test("Render text input without crashing", () => {
   const { getByLabelText } = render(<TextInputMUI control={}/>);
   const textField = getByLabelText(/A simple MIU text field/);
});

现在,问题是我不知道如何在我的测试中将控制作为参数传递。

有人可以帮忙吗?

为了以后参考,上面问题的解法有二三。

First,而不是将 control 作为 prop 向下传递给嵌套组件,您可以使用 useFormContext 访问表单上下文。文档 here.

    imports ...
    const schema = yup.object().shape({...});
    function App() {
      const methods = useForm({
        resolver: yupResolver(schema)
      });
      const { register, handleSubmit, formState: { errors }} = methods;
    
      return (
        <FormProvider {...methods}>
          <form onSubmit={handleSubmit((data) => console.log(data))}>
            <NestedInput/>
          </form>
        </FormProvider>
      );
    }

其次,您需要重构嵌套组件以访问表单上下文,如下所示:


    imports . . . 
    import { Controller, useFormContext } from 'react-hook-form'
    
    const NestedMUIinput = () => {
      const { control, ...rest } = useFormContext()
    
      return (
        <Controller
          name='nestedMUIinput'
          defaultValue=''
          control={control}
          render={({ field }) =>
            <TextField
              {...field}
              variant='outlined'
              margin='normal'
              fullWidth
              label='Nested input:'
              {...rest}
            />}
        />
      )

第三,在你的测试文件中,你需要用Provider包裹<NestedMUIinput />

imports . . .
import { useForm, FormProvider } from 'react-hook-form'
import NestedMUIinput from './NestedMUIinput'

const WrapperForm = ({ children }) => {
  const methods= useForm()
  return (
    <FormProvider {...methods}>
      {children}
    </FormProvider>
  )
}

test('Render text input without crashing', () => {
  const { getByLabelText } = render(<WrapperForm><NestedMUIinput /></WrapperForm>)
  const textField = getByLabelText(/Nested input:/)
})