如何使用jest测试useFormContext(react-hook-form)

niknxzdl  于 2023-06-20  发布在  Jest
关注(0)|答案(2)|浏览(150)

我有一个CDOB组件和一个DOB组件,它们使用了Mds表单元素和react-hook-form的useFormContext。我想为useFormContext方法(如watch)编写一个测试用例。
下面是组件的代码:

export default function CDOB(props){
  const { addr } = props;
  const { watch } = useFormContext();
  const code = watch(addr) ;

  const getMsg =() => {
    if(code == 'AL'){ return 'Invalid state'}
    else {return 'Invalid entry'}
  }

  return( <DOB keys={age: getMsg()}/>)
}

DOB组件代码:

export default function DOB(props){
  const { age } = props;
  const { watch, setValue } = useFormContext();
  const code = watch(addr) ;

  const getMsg =() => {
    if(code == 'AL'){ return 'Invalid state'}
    else {return 'Invalid entry'}
  }

  return ( <MdsTextInput 
            onChange={props.onChange}
            ....
          />
    )
  
}

如何使用Jest测试useFormContext的watch方法?

4nkexdtk

4nkexdtk1#

EN-USA:你需要模拟一个“useFormContext”PT-BR:准确地说是模仿“useFormContext”

import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import CDOB from './CDOB';

jest.mock('react-hook-form', () => ({
  useFormContext: jest.fn().mockReturnValue({
    watch: jest.fn(),
  }),
}));

describe('CDOB', () => {
  it('should display the correct message based on the code', () => {
    const mockWatch = jest.fn().mockReturnValue('AL');
    const mockUseFormContext = jest.requireMock('react-hook-form').useFormContext;
    mockUseFormContext.mockReturnValue({
      watch: mockWatch,
    });

    render(<CDOB addr="example" />);

    expect(screen.getByText('Invalid state')).toBeInTheDocument();
  });

  it('should display the default message for invalid codes', () => {
    const mockWatch = jest.fn().mockReturnValue('XX');
    const mockUseFormContext = jest.requireMock('react-hook-form').useFormContext;
    mockUseFormContext.mockReturnValue({
      watch: mockWatch,
    });

    render(<CDOB addr="example" />);

    expect(screen.getByText('Invalid entry')).toBeInTheDocument();
  });
});
jw5wzhpr

jw5wzhpr2#

您可以从用户的Angular 以测试任何其他表单的相同方式进行测试,而不必担心组件中的实现细节。你需要使用react-testing-library和jest来做,因为单独使用jest无法挂载组件。并模拟用户操作,如单击/键入/提交,并检查错误消息“Invalid state”和“Invalid entry”是否在正确的位置。

相关问题