enzyme学习记录之Shallow,Mount,render的区别
本文最后更新于:2021/02/20 , 星期六 , 18:38
render
1 | |
通过跟进方法可以看到注释表明:是将React组件渲染为HTML结构。
通过查阅资料又得出:该render方法仅调用组件内的render方法,但是会渲染全部的子组件
shallow
浅渲染,一个真正的单元测试。子组件并不会渲染。渲染的结果为React树。
在调用该方法时,会调用组件内的生命周期:constructor和render。
在使用该方法渲染后会得到一个:ShallowWrapper,ShallowWrapper内部又包含又setProps方法,在调用setProps方法时,则会调用生命周期:
componentWillReceivePropsshouldComponentUpdatecomponentWillUpdaterender
当ShallowWrapper调用unmount方法时,仅调用生命周期的componentWillUnmount
mount
测试componentDidMount和componentDidUpdate的唯一方式,会渲染包括子组件在内的所有组件。渲染结果为React树
在调用该方法时,会调用组件内的生命周期
constructorrendercomponentDidMount
使用mount的返回值为ReactWrapper,也可以调用setProps方法,调用的生命周期为componentWillReceivePropsshouldComponentUpdatecomponentWillUpdaterendercomponentDidUpdate
在使用unmount时,componentWillUnmount
总结
- 如果需要测试
componentDidMount和componentDidUpdate,就使用mount - 如果没必要渲染子组件,使用
shallow - 如果不涉及到生命周期函数,使用
render
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!