Skip to content

Capture intermediate updates when hook rerenders #461

Closed
@alaboudi

Description

@alaboudi

What is your question:

Let's consider the following hook

const useCounter = () => {
    const [counter, setCounter] = React.useState(0);

    React.useEffect(() => {
        setCounter(1)
    }, [])

    return counter;
}

export default useCounter;

when running a test using RHTL, the following passes:

describe('useCounter', () => {
   it('should  provide the initial count', () => {
       const { result } = renderHook(() => useCounter());
       expect(result.current).toBe(1); // ----> this passes 🟢
   });
});

But this test does not capture the actual behavior of how a component consumes a hook during different render cycles

function App() {
  const counter = useCounter();
  console.log('counter', counter);
 return counter; // returns 0 during first render and then returns 1 during second render.
}

Is there a way to test the output of the first render using RHTL? I'm currently in a situation where I just fixed a bug related to variable initialization in a custom hook and it would be nice to be able to add a test to increase my code coverage.

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requestedreleasedrequest for commentDiscussion about changes to the library

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions