这是我的ScrollWatcher.tsx组件
import { useEffect } from 'react';
interface Props {
onReachBottom: () => void;
}
export const ScrollWatcher = ({ onReachBottom }: Props) => {
useEffect(() => {
const handleScroll = () => {
if (
window.innerHeight + document.documentElement.scrollTop ===
document.documentElement.offsetHeight
) {
onReachBottom();
}
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, [onReachBottom]);
return <div />;
};
这是我的考验
import '@testing-library/jest-dom';
import { fireEvent, render } from '@testing-library/react';
import { ScrollWatcher } from './ScrollWatcher';
describe('ScrollWatcher', () => {
it('should call the onReachBottom function when the user scrolls to the bottom of the page', () => {
const onReachBottom = jest.fn();
const { container } = render(<ScrollWatcher onReachBottom={onReachBottom} />);
const scrollableContainer = container.parentElement;
fireEvent.scroll(scrollableContainer, { target: { scrollingElement: { scrollTop: 100 } } });
expect(onReachBottom).not.toHaveBeenCalled();
fireEvent.scroll(scrollableContainer, {
target: { scrollingElement: { scrollTop: scrollableContainer.scrollHeight } },
});
expect(onReachBottom).toHaveBeenCalled();
});
});
如果我把这个组件挂载到页面上,然后滚动到页面底部,它就可以工作了,但是如果我在测试中这样做,我会得到这个
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
我的测试写得不对吗?什么是合适的测试方法?
1条答案
按热度按时间w1jd8yoj1#
Jestjs底层使用JSDOM来模拟一个类似浏览器的环境。但是JSDOM还没有实现一个布局系统。请参见web平台的未实现部分issues#2843和issues#135。
因此,您必须模拟
window.innerHeight
、document.documentElement.scrollTop
和document.documentElement.offsetHeight
属性。例如
ScrollWatcher.tsx
:ScrollWatcher.test.tsx
:试验结果: