I created a React component that renders a Loading spinner. The component expects a function 'setShouldLoad' as a prop. Whenever the spinner is scrolled into view, it should call that 'setShouldLoad' function with the value true. I am using the IntersectionObserver API to make it happen. The code I wrote works fine and I was able to write a test in Cypress for it.
I would also like to write a unit test in jest for it to test. Any suggestion on how to tackle this issue? I am currently using the react testing-library.
Here is the code for the component so far:
import React, { FC, useEffect, useRef } from "react";
import LoadingSpinner from "../loadingSpinner";
type Props = {
setShouldLoad: React.Dispatch<React.SetStateAction<boolean>>;
};
const InfiniteScroller: FC<Props> = ({ setShouldLoad }) => {
const scrollTriggerElementRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const loadingSpinner = scrollTriggerElementRef.current!;
const observer = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting) {
setShouldLoad(true);
}
});
observer.observe(loadingSpinner);
return () => {
observer.unobserve(loadingSpinner);
observer.disconnect();
};
}, []);
return (
<div
ref={scrollTriggerElementRef}
className="InfiniteScroller w-full flex justify-center mb-10"
>
<LoadingSpinner />
</div>
);
};
export default InfiniteScroller;
Here is the test file so far :
import React from "react";
import { expect, describe, it } from "@jest/globals";
import { render, fireEvent } from "@testing-library/react";
import InfiniteScroller from ".";
describe("InfiniteScroller should work as expected", () => {
it("should render without crashing", () => {
expect(render(<InfiniteScroller setShouldLoad={() => {}} />)).toBeTruthy();
});
it("should call the setShouldLoad function with true when scrolled into view", () => {
const setShouldLoad = jest.fn();
// ???
fireEvent.scroll(loadingSpinner);
expect(setShouldLoad).toHaveBeenCalledWith(true);
});
});