Mocking click Height and scrollHeight in React + Enzyme for testing

We have a React component called a ScrollContainer than calling the prop function when its contents scroll down.

Basically:

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 in the rendering method is set as follows:

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

I want to test this logic with Jest + Enzyme.

I need a way to make the clientHeight, scrollHeight and scrollTop properties be the values โ€‹โ€‹of my choice for a test script.

With mounting instead of small, I can get these values, but they are always 0. I have yet to find a way to set them to anything but zero. I can set the container to wrapper.instance().container = { scrollHeight: 0 }, etc., but that only changes the test context, not the actual component.

Any suggestions would be appreciated!

+9
2

JSDOM - DOM - , , , . , . :

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

. ; , / .

+5

Jest SpyOn 22.1. 0+.

, document.documentElement.scrollHeight

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

100 scrollHeight.

0

Source: https://habr.com/ru/post/1690818/


All Articles