【问题标题】:Mocking clientHeight and scrollHeight in React + Enzyme for test在 React + Enzyme 中模拟 clientHeight 和 scrollHeight 进行测试
【发布时间】:2018-05-29 03:34:09
【问题描述】:

我们有一个名为 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 而不是 shallow 我可以获得这些值,但它们始终为 0。我还没有找到任何方法将它们设置为非零值。我可以在wrapper.instance().container = { scrollHeight: 0 } 等上设置容器,但这只会修改测试上下文而不是实际组件。

任何建议将不胜感激!

【问题讨论】:

    标签: reactjs unit-testing jestjs enzyme


    【解决方案1】:

    简化的解决方案只需要模拟useRefcreateRef,因为被测组件取决于useRef 的返回值:

    import { useRef } from 'react';
    
    jest.mock('react', () => ({
      ...jest.requireActual('react'),
      useRef: jest.fn(),
    }));
    
    test('test ref', () => {
      useRef.mockReturnValue({
        // insert required properties here
      });
      // do assertions as normal
    });
    

    【讨论】:

      【解决方案2】:

      Jest spyOn 可用于模拟 22.1.0+ 版本的 getter 和 setter。见jest docs

      我使用下面的代码来模拟 document.documentElement.scrollHeight

      的实现
      const scrollHeightSpy = jest
                          .spyOn(document.documentElement, 'scrollHeight', 'get')
                          .mockImplementation(() => 100);
      

      它返回 100 作为 scrollHeight 值。

      【讨论】:

        【解决方案3】:

        JSDOM 不做任何实际的渲染——它只是模拟 DOM 结构——所以像元素尺寸这样的东西不会像你想象的那样计算出来。如果您通过方法调用获取维度,则可以在测试中模拟这些维度。例如:

         beforeEach(() => {
            Element.prototype.getBoundingClientRect = jest.fn(() => {
                  return { width: 100, height: 10, top: 0, left: 0, bottom: 0, right: 0 };
                });
          });
        

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

        另见this thread

        【讨论】:

          猜你喜欢
          • 2021-09-27
          • 1970-01-01
          • 1970-01-01
          • 2017-03-06
          • 2016-10-14
          • 2014-05-05
          • 2020-11-25
          • 2018-08-31
          • 1970-01-01
          相关资源
          最近更新 更多