0

I have this hook in React I want to write the unit test but I faced the problem that I don't know how I could cover handleScroll function, how can I go to the useEffect to trigger the scroll event?

I tried fireEvent.scroll but not success.

import { useState, useEffect } from 'react';

const scrollWindow = (
  fetchOffset: number,
  callback: () => void,
  preventFetch?: boolean,
) => {
  const [isFetching, setIsFetching] = useState(false);

  const handleScroll = () => {
    const scrollFromBottom = docElem.scrollHeight - docElem.scrollTop - docElem.clientHeight;
    if (scrollFromBottom - fetchOffset > 0) return;
    setIsFetching(true);
  };

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [isFetching, preventFetch]);

  useEffect(() => {
    if (!isFetching) return;
    callback();
  }, [isFetching]);

  return [isFetching, setIsFetching];
};

export default scrollWindow;
iceCream
  • 3
  • 2

0 Answers0