0

I have multiple useState in react component. Some states are set from event handler of component. How to mock such instance of state using jest and react-testing-library ?

Example:

function Component () {
     const [isEnabled, setIsEnabled] = useState(false)
     const [isClick, setIsClick] = useState(false)
     const [isData, setIsData] = useState(false)

     const handleData = () => {
          setIsClick(true)
     }

     return(
          <div>
               //form component
               <button onSubmit={handleData}>Submit</>
          </div>
     )
}

Akshay phalphale
  • 145
  • 3
  • 14
  • Why do you need to do this? testing-library doesn't want users to mess with internal state. https://testing-library.com/docs/dom-testing-library/faq – evolutionxbox Jun 15 '22 at 13:23
  • @evolutionxbox When I check test coverage, local state are not covered. I can satisfy those condition by mocking those instance. or is there any way to pass mock value of state to component ? – Akshay phalphale Jun 15 '22 at 13:31
  • Don't. Don't mock _any_ `useState`. Test the _behaviour_ - simulate the button click, and assert on the observable change to the `isClick` state. In general, test things through their public interfaces - for a React component that's the props, the rendered DOM and any interactions with collaborators (e.g. services, where test doubles would be more appropriate). – jonrsharpe Jun 15 '22 at 13:38
  • Things that are not covered are not being used. This is ok – evolutionxbox Jun 15 '22 at 14:30
  • I resolved this issue on this way: https://stackoverflow.com/a/75210440/731329 – lortschi Jan 23 '23 at 14:01

0 Answers0