reactjs – 在React Enzyme中模拟clientHeight和scrollHeight进行测试

前端之家收集整理的这篇文章主要介绍了reactjs – 在React Enzyme中模拟clientHeight和scrollHeight进行测试前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们有一个名为ScrollContainer的React组件,当它的内容滚动到底部调用prop函数.

基本上:

  1. componentDidMount() {
  2. const needsToScroll = this.container.clientHeight != this.container.scrollHeight
  3.  
  4. const { handleUserDidScroll } = this.props
  5.  
  6. if (needsToScroll) {
  7. this.container.addEventListener('scroll',this.handleScroll)
  8. } else {
  9. handleUserDidScroll()
  10. }
  11. }
  12.  
  13. componentWillUnmount() {
  14. this.container.removeEventListener('scroll',this.handleScroll)
  15. }
  16.  
  17. handleScroll() {
  18. const { handleUserDidScroll } = this.props
  19. const node = this.container
  20. if (node.scrollHeight == node.clientHeight + node.scrollTop) {
  21. handleUserDidScroll()
  22. }
  23. }

this.container在render方法中设置如下:

  1. <div ref={ container => this.container = container }>
  2. ...
  3. </div>

我想用Jest Enzyme测试这个逻辑.

我需要一种方法来强制clientHeight,scrollHeight和scrollTop属性为我为测试场景选择的值.

使用mount而不是浅,我可以获得这些值,但它们始终为0.我还没有找到任何方法将它们设置为非零值.我可以在wrapper.instance().container = {scrollHeight:0}等设置容器,但这只会修改测试上下文而不是实际组件.

任何建议,将不胜感激!

JSDOM不进行任何实际渲染 – 它只是模拟DOM结构 – 所以像元素尺寸这样的东西不会像你期望的那样计算.如果您通过方法调用获取维度,则可以在测试中模拟这些维度.例如:
  1. beforeEach(() => {
  2. Element.prototype.getBoundingClientRect = jest.fn(() => {
  3. return { width: 100,height: 10,top: 0,left: 0,bottom: 0,right: 0 };
  4. });
  5. });

这显然不适用于您的示例.可以在元素上覆盖这些属性并模拟对它们的更改;但我怀疑这不会导致特别有意义/有用的测试.

另见this thread

猜你在找的React相关文章