【发布时间】:2019-10-01 09:08:20
【问题描述】:
我在 react 组件中有这样的功能:
handleOnScroll = () => {
const {navigationSections, setNavigationSectionActive} = this.props;
const reversedSections = this.getReversedNavigationSections();
const OFFSET_TOP = 32;
const st = window.pageYOffset || document.documentElement.scrollTop;
if (st > lastScrollTop) {
for (let i = 0; i < navigationSections.length; i += 1) {
if(document.getElementById(navigationSections[i].id).getBoundingClientRect().top <= OFFSET_TOP) {
setNavigationSectionActive(navigationSections[i].id);
}
}
} else if (st < lastScrollTop) {
for (let y = 0; y < reversedSections.length; y += 1) {
if(document.getElementById(navigationSections[y].id).getBoundingClientRect().top <= OFFSET_TOP) {
setNavigationSectionActive(navigationSections[y].id);
}
}
}
lastScrollTop = st <= 0 ? 0 : st;
}
还有一些这样的测试:
it('should handle handleOnScroll', () => {
instance.handleOnScroll();
expect(instance.getReversedNavigationSections()).toEqual(props.navigationSections.reverse());
});
props.navigationSections.forEach(navSection => {
it('should call setNavigationSectionActive', () => {
instance.handleOnScroll();
expect(props.setNavigationSectionActive).toHaveBeenCalledWith(navSection.id);
});
});
如您所见,第一个测试通过但第二个测试('应该调用 setNavigationSectionActive')失败:
我认为原因是因为文档没有被模拟,因此 if 失败。但是,在实际执行时:
document.getElementById(navigationSections[i].id).getBoundingClientRect().top
具有这些 ID 的 DIV 位于另一部分(不在用于相关测试的包装器组件中)。
我应该模拟文档以模拟 if 语句通过的实际结构还是我完全错了?
到目前为止我的尝试
it('should handle custom handleOnScroll', () => {
document.body.innerHTML = '<div><div id="id">my div</div><div id="id-1">my div</div></div>';
const div = document.getElementById('id');
div.getBoundingClientRect = () => ({ top: 100 }); // <= mock getBoundingClientRect
instance.handleOnScroll();
props.navigationSections.forEach(() => {
if (global.document.getElementById('id').getBoundingClientRect().top <= global.OFFSET_TOP) {
expect(props.setNavigationSectionActive).toHaveBeenCalledWith('id');
}
});
});
【问题讨论】:
标签: javascript unit-testing jestjs