Jos*_*h G 10 unit-testing reactjs jestjs enzyme
我们有一个名为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()
}
}
Run Code Online (Sandbox Code Playgroud)
this.container 在render方法中设置如下:
<div ref={ container => this.container = container }>
...
</div>
Run Code Online (Sandbox Code Playgroud)
我想用Jest + Enzyme测试这个逻辑.
我需要一种方法来强制clientHeight,scrollHeight和scrollTop属性成为我为测试场景选择的值.
使用mount而不是浅,我可以获得这些值,但它们始终为0.我还没有找到任何方法将它们设置为非零值.我可以设置容器wrapper.instance().container = { scrollHeight: 0 }等等,但这只会修改测试上下文而不是实际组件.
任何建议,将不胜感激!
kam*_*esh 18
Jest spyOn 可用于模拟 22.1.0+ 版本的 getter 和 setter。见笑话文档
我使用下面的代码来模拟document.documentElement.scrollHeight 的实现
const scrollHeightSpy = jest
.spyOn(document.documentElement, 'scrollHeight', 'get')
.mockImplementation(() => 100);
Run Code Online (Sandbox Code Playgroud)
它返回 100 作为 scrollHeight 值。
JSDOM并没有做任何实际的渲染-它只是模拟DOM结构-因此像元素尺寸之类的东西并没有像您期望的那样计算。如果您通过方法调用获取维度,则可以在测试中模拟它们。例如:
beforeEach(() => {
Element.prototype.getBoundingClientRect = jest.fn(() => {
return { width: 100, height: 10, top: 0, left: 0, bottom: 0, right: 0 };
});
});
Run Code Online (Sandbox Code Playgroud)
这显然在您的示例中不起作用。可以覆盖元素上的这些属性并模拟对它们的更改;但我怀疑这不会导致特别有意义/有用的测试。
另请参阅此线程