迁移至8后无法模拟React-Rect-Redux钩子

发布于 2025-01-26 05:40:45 字数 941 浏览 1 评论 0原文

我一直在使用以下模式在使用酶浅渲染的测试中模拟React-Redux钩子:

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

但是,在迁移到React-React-Redux 8.0.1(来自7.2.6)之后,此模式不再有效,我将获得以下内容错误:

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

我怀疑这与React-Redux的内部变化有关(在8.x发行说明中被吞噬)。有人有任何有关如何克服这一问题的提示吗?我尝试将渲染效果包装在提供商中,然后使用dive()

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

但是,这抛出了“找不到React-Redux上下文值;请确保将组件包装在A&lt; Provider; Provider&gt;中。。此外,虽然这将有助于use -elector,但对于模拟usedispatch而言,它不太有用。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

厌倦 2025-02-02 05:40:45

我有同样的问题

我的解决方案

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

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);
        });
    });
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文