how to detect scrollPosition with fireEvent.scroll? - React-testing-library
Asked Answered
P

1

12

[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.

Peppers answered 13/6, 2020 at 16:51 Comment(1)
Have you had any luck in scrolling?Kalagher
A
0
  • 1- first you can create a div/section with a fixed height and then set its overflow property to scroll.

  • 2- add some content to the div and scroll it programmatically using the scrollTop property.

  • 3- you can fire a scroll event on the div/section and check the scrollTop value

Airfoil answered 11/3, 2023 at 15:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.