迁移到 8 后无法模拟 react-redux 挂钩

Unable to mock react-redux hooks after migrating to 8

我一直在使用以下模式在使用 Enzyme 浅渲染的测试中模拟 react-redux 挂钩:

import * as redux from "react-readux";
...
jest.spyOn(redux, "useSelector").mockReturnValue(Generator.generateUser());

但是,在迁移到 react-redux 8.0.1(从 7.2.6)之后,这个模式不再有效,我收到以下错误:

TypeError: Cannot redefine property: useSelector
        at Function.defineProperty (<anonymous>)

我怀疑这与 react-redux 内部的变化有关(如 8.x 发行说明中所公布)。有没有人对如何克服这个问题有任何建议?我尝试将渲染包装在 Provider 中并使用 dive():

const wrapper = shallow(<Provider store={mockStore}>
<WrappedComponent />
</Provider>);
expect(wrapper.find(WrappedComponent).dive().isEmptyRender()).toBeTruthy();

但这会抛出 "could not find react-redux context value; please ensure the component is wrapped in a <Provider>"。此外,虽然这对 useSelector 有帮助,但它对模拟 useDispatch.

的用处不大

我遇到了同样的问题

我的解决方案

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);
        });
    });
});