在React + Enzyme中模拟clientHeight和scrollHeight进行测试 [英] Mocking clientHeight and scrollHeight in React + Enzyme for test
问题描述
我们有一个名为ScrollContainer的React组件,当其内容滚动到底部时,它会调用prop函数。
We have a React component called ScrollContainer than calls a prop function when its content is scrolled to the bottom.
基本上:
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方法中设置如下:
this.container
is set as follows in the render method:
<div ref={ container => this.container = container }>
...
</div>
我想使用Jest + Enzyme测试这种逻辑。
I want to test this logic using Jest + Enzyme.
我需要一种方法来强制将clientHeight,scrollHeight和scrollTop属性设置为我为测试方案选择的值。
I need a way to force the clientHeight, scrollHeight and scrollTop properties to be values of my choosing for the test scenario.
使用mount而不是shallow可以获取这些值,但它们始终为0。我尚未找到任何方法将它们设置为非零值。我可以在 wrapper.instance()。container = {scrollHeight:0}
等上设置容器,但这只会修改测试上下文,而不是实际的组件。
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.
任何建议将不胜感激!
推荐答案
玩笑spyOn可以用来模拟版本22.1.0及更高版本中的getter和setter。请参见最好的文档
Jest spyOn can be used to mock getter and setter from version 22.1.0+. See jest docs
我使用下面的代码来模拟 document.documentElement.scrollHeight
I used below code to mock implementation of document.documentElement.scrollHeight
const scrollHeightSpy = jest
.spyOn(document.documentElement, 'scrollHeight', 'get')
.mockImplementation(() => 100);
它返回100作为scrollHeight值。
It returns 100 as scrollHeight value.
这篇关于在React + Enzyme中模拟clientHeight和scrollHeight进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!