我们有一个名为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()
}
}
在render方法中,this.container
的设置如下:
<div ref={ container => this.container = container }>
...
</div>
我想用Jest +酶来测试这个逻辑。
我需要一种方法来强制clientHeight、scrollHeight和scrollTop属性成为我在测试场景中选择的值。
使用mount而不是shallow,我可以得到这些值,但它们始终是0。我还没有找到任何方法来将它们设置为非零。我可以在wrapper.instance().container = { scrollHeight: 0 }
等上设置容器,但这只会修改测试上下文,而不是实际的组件。
如有任何建议,我们将不胜感激!
发布于 2019-06-05 17:32:17
Jest spyOn可用于模拟22.1.0+版本中的getter和setter。请参阅jest docs
我使用了以下代码来模拟document.documentElement.scrollHeight的实现
const scrollHeightSpy = jest
.spyOn(document.documentElement, 'scrollHeight', 'get')
.mockImplementation(() => 100);
它返回100作为scrollHeight值。
发布于 2018-06-05 22:19:14
JSDOM并不做任何实际的渲染--它只是模拟DOM结构--所以像元素尺寸这样的东西不会像你所期望的那样被计算出来。如果您通过方法调用获取维度,则可以在测试中模拟这些维度。例如:
beforeEach(() => {
Element.prototype.getBoundingClientRect = jest.fn(() => {
return { width: 100, height: 10, top: 0, left: 0, bottom: 0, right: 0 };
});
});
这显然不会在您的示例中起作用。可以覆盖元素上的这些属性并模拟对它们的更改;但我怀疑这不会产生特别有意义/有用的测试。
另请参阅this thread
发布于 2021-06-07 15:58:24
简化的解决方案只需要模拟useRef
或createRef
,因为测试中的组件依赖于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
});
https://stackoverflow.com/questions/47823616
复制相似问题