How to set initial state for useState Hook in jest and enzyme?

You can mock React.useState to return a different initial state in your tests:

// Cache original functionality
const realUseState = React.useState

// Stub the initial state
const stubInitialState = ['stub data']

// Mock useState before rendering your component
  .spyOn(React, 'useState')
  .mockImplementationOnce(() => realUseState(stubInitialState))


Leave a Comment