Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking clientHeight and scrollHeight in React + Enzyme for test

We have a React component called ScrollContainer than calls a prop function when its content is scrolled to the bottom.

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

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

I want to test this logic using Jest + Enzyme.

I need a way to force the clientHeight, scrollHeight and scrollTop properties to be values of my choosing for the test scenario.

With mount instead of shallow I can get these values but they are always 0. I have yet to find any way to set them to anything non zero. I can set the container on wrapper.instance().container = { scrollHeight: 0 } and etc, but this only modifies the test context not the actual component.

Any suggestions would be appreciated!

like image 326
Josh G Avatar asked Dec 14 '17 23:12

Josh G


1 Answers

Jest spyOn can be used to mock getter and setter from version 22.1.0+. See jest docs

I used below code to mock implementation of document.documentElement.scrollHeight

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

It returns 100 as scrollHeight value.

like image 107
kamlesh Avatar answered Sep 24 '22 02:09

kamlesh