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

huangapple go评论117阅读模式
英文:

How to test useFormContext(react-hook-form) using jest

问题

以下是您要求的翻译部分:

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?

英文:

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 =() =&gt; {
    if(code == &#39;AL&#39;){ return &#39;Invalid state&#39;}
    else {return &#39;Invalid entry&#39;}
  }

  return( &lt;DOB keys={age: getMsg()}/&gt;)
}

Code for DOB component:

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

  const getMsg =() =&gt; {
    if(code == &#39;AL&#39;){ return &#39;Invalid state&#39;}
    else {return &#39;Invalid entry&#39;}
  }

  return ( &lt;MdsTextInput 
            onChange={props.onChange}
            ....
          /&gt;
    )
  
}

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

答案1

得分: 0

你可以以与测试任何其他表单相同的方式进行测试,从用户的角度来看,而不必担心将实现细节放入组件中。
你需要使用react-testing-library和jest来执行这些操作,因为仅使用jest无法挂载组件。然后模拟用户操作,如点击/输入/提交,并检查你的错误消息 "Invalid state" 和 "Invalid entry" 是否放置在正确的位置。

英文:

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.

答案2

得分: 0

EN-USA: You need to mock a "useFormContext"
PT-BR: Você precisa mockar um "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();
  });
});
英文:

EN-USA: You need to mock a "useFormContext"
PT-BR: Você precisa mock a "useFormContext"

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

jest.mock(&#39;react-hook-form&#39;, () =&gt; ({
  useFormContext: jest.fn().mockReturnValue({
    watch: jest.fn(),
  }),
}));

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

    render(&lt;CDOB addr=&quot;example&quot; /&gt;);

    expect(screen.getByText(&#39;Invalid state&#39;)).toBeInTheDocument();
  });

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

    render(&lt;CDOB addr=&quot;example&quot; /&gt;);

    expect(screen.getByText(&#39;Invalid entry&#39;)).toBeInTheDocument();
  });
});

huangapple
  • 本文由 发表于 2023年6月5日 23:58:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76408149.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定