javascriptreactjsjestjsreact-testing

mock value inside the component file


I would like to ask if I have the variable useState in the component which is used as a condition that determines the element inside it will appear or not. How to mock the variable? So that I can test the element inside the condition if the value is 'login'.

   const [dataHistory,seDataHistory] = useState("")
   const [data,setData] = useState("firstTimeLogin")
        
    const func2 = () => {
     getData({
      item1: "0",
     }).
     then((res) => {
       funct();
     })
   }

   const funct = () => 
     {setData("login")}
        
   return  
     {data === "firstTimeLogin" && (
        <div><button onClick="funct2()">next</button></div>
     )}

     {data === "login" && (
        <div>flow login</div>
      )}

Solution

  • Firstly, you need to add data-testid for your button

    {data === "firstTimeLogin" && (
       <div><button onClick="funct2" data-testid="next-button">next</button></div>
    )}
    

    You called onClick="funct2()" which is to trigger funct2 immediately after re-rendering, so I modified it to onClick="funct2".

    Note that you also can use next content in the button for the event click but I'd prefer using data-testid is more fixed than next content.

    In your test file, you should mock getData and call fireEvent.click to trigger funct2()

    import { screen, fireEvent, render } from '@testing-library/react';
    
    //'/getData' must be the actual path you're importing for `getData` usage
    jest.mock('/getData', () => {
       return {
          getData: () => new Promise((resolve) => { resolve('') }) // it's mocked, so you can pass any data here
       }
    })
    
    it('should call funct', async () => {
       render(<YourComponent {...yourProps}/>)
       const nextButton = await screen.findByTestId("next-button"); //matched with `data-testid` we defined earlier
       fireEvent.click(nextButton); //trigger the event click on that button
       const flowLoginElements = await screen.findByText('flow login'); //after state changes, you should have `flow login` in your content
       expect(flowLoginElements).toBeTruthy();
    })