skip to Main Content

I have a CDOB component and a DOB component that are using Mds form elements and react-hook-form’s useFormContext.
I want to write a test case for the useFormContext methods such as watch.

Here is the code for the components:

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()}/>)
}

Code for DOB component:

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}
            ....
          />
    )
  
}

How can I test useFormContext’s watch method using Jest?

2

Answers


  1. You can test in the same way you would test any other form, from the user’s point of view without worrying about the implementation details into the component.
    You will need to use react-testing-library with jest to do that jest alone can not mount the component. And simulate user actions like click/type/submit and check if your error messages "Invalid state" and "Invalid entry" are in the right place.

    Login or Signup to reply.
  2. EN-USA: You need to mock a "useFormContext"
    PT-BR: Você precisa mock a "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();
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search