Skip to content

How to verify multiple calls to state in a test #216

@SachinSaggezza

Description

@SachinSaggezza

I am trying to call multiple calls to decrement counter hook in a same test. It's crucial for me to be able to verify the result after multiple calls.
Here is my implementation code.

export default function useCount({initial=0})
{
    const [count,setCount]=React.useState(initial);
    const increment = React.useCallback( ()=>{setCount(count+1)},[]);
    const decrement =React.useCallback( ()=>{
        setCount(count-1);
    },[]);
    const reset = ()=>{};
    return {count,increment,decrement,reset};
    

}

and here is my test code

const getProps = (props={})=>{
    return {...props,initial:0};
}
const setup  = () =>{
    return UseCount(getProps());
}
   test("should decrement",   ()=>{
        const {result,waitForNextUpdate,rerender} = renderHook ( ()=>setup());
        act(  ()=>{
         
            result.current.decrement();
            result.current.decrement();
        })
        expect(result.current.count).toBe(-2);
   });
});

In the results even though i can verify calls are being made to decrement function, however, it seems state is updated only one time(specifically the last time).

Can you tell me what needs to be done?

Here is my react and testing version

 "react": "^16.11.0",
  "@testing-library/react-hooks": "^3.2.1",

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions