Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

177
Views
How to unit test a React component that uses an IntersectionOberserver with Jest

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);
  });
});
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!