Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

185
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda