为什么 useState 不会在单元测试(Jest、Enzyme)中重新呈现组件?



我在 Jest 中重新渲染酶包装组件时遇到问题。我花了一段时间才缩小问题范围,但这似乎是useState和酶的问题。

我有一个带有按钮的组件。单击该按钮将调用setState()函数以更新组件状态并重新呈现。例如:

// ...
<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>
// ...

在此示例中,setShowInfoDrawer()useState()钩子的一部分,作为 prop 从父组件传递下来。

当我运行测试时(请参阅下面的示例(,单击模拟似乎有效,但组件不会重新渲染。

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

我做了一些研究,似乎有一段时间 Enzyme 不支持useState,但它是这个 PR 中的地址,看起来它是与 3.11.0 版本一起发布的,甚至可能是 3.10.0(我使用的是 3.11.0,最新的(。

我做错了什么?是因为setShowInfoDrawer()来自父组件吗?如果是这样,我该如何让它工作?

好吧,我想通了。事后看来,这是很明显的。我需要将此测试作为父组件(即打开抽屉并具有useState()钩的组件(的测试运行,而不是作为抽屉组件本身的单元测试。

最新更新