[英]Why is useState not re-rendering the component in a unit test (Jest, Enzyme)?
I'm having trouble re-rendering an Enzyme-wrapped component in Jest.我无法在 Jest 中重新渲染酶包装的组件。 It took me a while to narrow down the problem, but it seems to be a problem with useState
and Enzyme.我花了一段时间才缩小问题范围,但似乎是useState
和 Enzyme 的问题。
I have a component with a button in it.我有一个带有按钮的组件。 Clicking the button calls a setState()
function to update component state and re-render.单击按钮调用setState()
function 以更新组件 state 并重新渲染。 For example:例如:
// ...
<Drawer
classes={{ paper: classes.drawer }}
anchor="right"
open={showInfoDrawer}
variant={mobile() ? 'temporary' : 'persistent'}
onClose={() => {
console.log('closing'); // to check onClose simulation works
setShowInfoDrawer(false);
}}
>
// rest of component...
</Drawer>
// ...
In this example, the setShowInfoDrawer()
is part of a useState()
hook, passed down as a prop from a parent component.在此示例中, setShowInfoDrawer()
是useState()
挂钩的一部分,作为来自父组件的 prop 向下传递。
When I run a test (see example below), the click simulation seems to work, but the component does not re-render.当我运行测试时(参见下面的示例),点击模拟似乎可以工作,但组件不会重新渲染。
test('should close ActivityInfoDrawer', () => {
expect(wrappedActivityInfoDrawer.find(Drawer)).toHaveLength(1);
const wrappedDrawer = wrappedActivityInfoDrawer.find(Drawer);
// @ts-ignore
act(() => wrappedDrawer.props().onClose()); // Logs "Clicked..."
wrappedActivityInfoDrawer.update();
expect(wrappedActivityInfoDrawer.find(Drawer)).toHaveLength(0); // Fails
});
I did some research and it seems that for a while Enzyme did not support useState
, but it was address in this PR , which looks like it was released with version 3.11.0, or maybe even 3.10.0 (I'm using 3.11.0, the latest).我做了一些研究,似乎有一段时间 Enzyme 不支持useState
,但它是这个PR中的地址,看起来它是随版本 3.11.0 发布的,甚至可能是 3.10.0(我使用的是 3.11. 0,最新)。
What am I doing wrong?我究竟做错了什么? Is it because setShowInfoDrawer()
comes from a parent component?是因为setShowInfoDrawer()
来自父组件吗? If so, how do I get it working?如果是这样,我该如何让它工作?
Okay, I figured it out.好吧,我想通了。 It's pretty obvious in hindsight.事后看来,这很明显。 I needed to running this test as a test for the parent component (ie, the component that opens the drawer and has the useState()
hook), rather than as a unit test for the Drawer component itself.我需要将此测试作为对父组件(即打开抽屉并具有useState()
挂钩的组件)的测试,而不是作为对 Drawer 组件本身的单元测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.