[For question purpose, I make dummy example to make it easier to understand]
Let's say I have this homepage component that will toggle color when reach 1/3 of page height.
// Homepage.js
const Home = (props) => {
const [toggle, setToggle] = useState(false)
useEffect(() => {
window.addEventListener('scroll', handleScroll)
return () => window.removeEventListener('scroll', handleScroll)
}, [toggle])
const handleScroll = () => {
const scrollPosition = document.documentElement.scrollTop;
const oneThirdPageHeight = (1 / 3) * document.documentElement.offsetHeight;
if (scrollPosition > onethirdPageHeight) {
return setToggle(true)
}
return setToggle(false)
}
return <div style={{ height: '1500px', color: toggle ? 'blue' : 'red'}}>hello</div>
}
and for the test file
// Homepage.test.js
test('should toggle color when scrolled', () => {
const { getByText } = render(<Homepage />);
const DivEl = getByText('hello');
expect(DivEl).toHaveStyle('color: red');
fireEvent.scroll(window, { target: { scrollY: 800 } });
expect(DivEl).toHaveStyle('color: blue'); // --> failing
});
It seems like I can't make the DOM scrolled by doing fireEvent.scroll(window, { target: { scrollY: 800 } })
. Where did I miss? Please help, thank you in advance.