Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 384
kidney Avatar asked Aug 30 '25 16:08

kidney


1 Answers

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);
        });
    });
});
like image 126
Ozee Avatar answered Sep 02 '25 07:09

Ozee