unit-testing - 如何对 React 组件的 shouldComponentUpdate 方法进行单元测试

标签 unit-testing reactjs enzyme

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

最佳答案

我可能会直接调用shouldComponentUpdate。

类似于

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

尝试通过确定组件是否实际渲染/未渲染来进行测试可能比其值(value)更麻烦;我什至不确定你如何使用 enzyme 来做到这一点。您不能真正放弃渲染的输出,因为除非渲染的输出与以前相同,否则您可能不会从 shouldComponentUpdate 返回 false。因此,无法仅根据输出来确定渲染是否发生。

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

关于unit-testing - 如何对 React 组件的 shouldComponentUpdate 方法进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44211414/

相关文章:

javascript - 如何通过单元测试检查字符串是否恰好出现 1 次?

javascript - 如何在 React 中单独切换多个显示

reactjs - 无法让 React Hook setInterval 计时器在 Jest/Enzyme 测试期间运行

reactjs - 使用 useState() 钩子(Hook)测试功能组件时设置状态

reactjs - 使用 Jest 和 Enzyme 进行测试时设置 URL 参数

angular - submitEl.triggerEventHandler 不是 Angular 5 中的函数

Python3 + pytest + pytest 模拟 : Mocks leaking into other test functions breaking assertions?

javascript - 未捕获( promise 中)SyntaxError : Unexpected end of input in React when fetching the API

android - 错误 : Bundling failed - While trying to resolve module 'react-native-firebase'

c# - 在单元测试项目中获取具有属性的程序集