'Unable to mock react-redux hooks after migrating to 8

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.



Solution 1:[1]

I had the same problem

My solution

import * as Redux from "react-redux";

jest.mock("react-redux", () => ({
    ...jest.requireActual("react-redux"),
    useSelector: jest.fn(),
}));

describe("Blabla", () => {
    const mockedState = {
        user: {
            firstname: "John",
        },
    };

    beforeEach(() => {
        Redux.useSelector.mockImplementation((callback) => {
            return callback(mockedState);
        });
    });
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ozee