加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 20:45:17 所属栏目:百科 来源:网络整理
导读:我们有一个名为ScrollContainer的React组件,当它的内容滚动到底部时调用prop函数. 基本上: componentDidMount() { const needsToScroll = this.container.clientHeight != this.container.scrollHeight const { handleUserDidScroll } = this.props if (nee
我们有一个名为ScrollContainer的React组件,当它的内容滚动到底部时调用prop函数.

基本上:

componentDidMount() {
  const needsToScroll = this.container.clientHeight != this.container.scrollHeight

  const { handleUserDidScroll } = this.props

  if (needsToScroll) {
    this.container.addEventListener('scroll',this.handleScroll)
  } else {
    handleUserDidScroll()
  }
}

componentWillUnmount() {
  this.container.removeEventListener('scroll',this.handleScroll)
}

handleScroll() {
  const { handleUserDidScroll } = this.props
  const node = this.container
  if (node.scrollHeight == node.clientHeight + node.scrollTop) {
    handleUserDidScroll()
  }
}

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

<div ref={ container => this.container = container }>
  ...
</div>

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

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

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

任何建议,将不胜感激!

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

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

另见this thread

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读