I have been using the following pattern to mock react-redux hooks in tests that use Enzyme shallow rendering:
import * as redux from "react-readux";
...
jest.spyOn(redux, "useSelector").mockReturnValue(Generator.generateUser());
However, after migration to react-redux 8.0.1 (from 7.2.6), this pattern no longer works and I am getting the following error:
TypeError: Cannot redefine property: useSelector
at Function.defineProperty (<anonymous>)
I suspect this has something to do with the changes in the internals of react-redux (as anounced in the 8.x release notes). Does anyone have any tips on how to overcome this? I tried wrapping the rendering in a Provider and using dive():
const wrapper = shallow(<Provider store={mockStore}>
<WrappedComponent />
</Provider>);
expect(wrapper.find(WrappedComponent).dive().isEmptyRender()).toBeTruthy();
But this throws "could not find react-redux context value; please ensure the component is wrapped in a <Provider>". Moreover, while this would help with useSelector, it is less useful for mocking useDispatch.