如何对React Component应该进行单元测试shouldComponentUpdate方法 [英] How to unit test React Component shouldComponentUpdate method

查看:66
本文介绍了如何对React Component应该进行单元测试shouldComponentUpdate方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个React组件,它实现了 shouldComponentUpdate 方法我想对其进行单元测试。理想情况下,我可以在单元测试中更改组件的某些属性或状态,并验证是否重新渲染。如果有帮助,我正在使用

I have a React Component that implements the shouldComponentUpdate method and I'd like to unit test it. Ideally I could change some prop or state on the component in a unit test and verify it either re-rendered or not. I am using enzyme if that helps.

推荐答案

我可能只是直接调用shouldComponentUpdate。

I would probably just call shouldComponentUpdate directly.

类似

const comp = shallow(<Comp {...props} />)
const shouldUpdate = comp.instance().shouldComponentUpdate(nextProps, nextState)
expect(shouldUpdate).toBe(true/false)

尝试通过确定组件是否实际渲染来进行测试/不渲染可能比它值得的麻烦更多;我什至不知道你会怎么用酶来做到这一点。您无法真正脱离渲染的输出,因为除非渲染的输出与以前相同,否则您可能不会从shouldComponentUpdate返回false。因此,仅从输出中就不能确定渲染是否发生。

Trying to test by determining if the component actually rendered/didn't render is probably more trouble than it's worth; I'm not even sure how you would do that using enzyme. You can't really go off of the rendered output, since you would probably not return false from shouldComponentUpdate unless the rendered output was the same as before. So determining if a render occurred or not couldn't come from the output alone.

直接调用它进行测试对我来说似乎很好。只要您相信React将正确使用您的shouldComponentUpdate返回值(如果没有,我们会遇到更大的问题),它就是安全的。

Testing by calling it directly seems fine to me though. As long as you trust React is going to use your shouldComponentUpdate return value correctly (we have bigger problems if it doesn't), it's safe.

这篇关于如何对React Component应该进行单元测试shouldComponentUpdate方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆