迁移至8后无法模拟React-Rect-Redux钩子
我一直在使用以下模式在使用酶浅渲染的测试中模拟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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我有同样的问题
我的解决方案
I had the same problem
My solution