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

114
Vistas
React-testing-library button click replacing dom elements rather than replicating them

I have a simple application that calls an API and adds an image to the DOM on click:

export const DogGallery = () => {
  const [dogPhotos, setDogPhotos] = useState([]);
  const getDogPhoto = async () => {
    const newPhoto = await fetch(
      "https://dog.ceo/api/breeds/image/random"
    ).then((res) => res.json());
    const photosArray = [...dogPhotos, newPhoto.message];
    setDogPhotos(photosArray);
  };
  return (
    <>
      <p>Dog gallery</p>
      <Button handleClick={getDogPhoto} />
      {dogPhotos.length > 0 &&
        dogPhotos.map((photo, i) => (
          <DogPhoto source={photo} key={i} number={i} />
        ))}
    </>
  );
};

However, when I test this in react-testing-library and fire the click even five times, I still end up with one image in the DOM.

const clickButton = () => {
  const buttonElement = screen.getByText("click!");
  fireEvent.click(buttonElement);
};

it("should render 5 images", async () => {
  render(<DogGallery />);
  clickButton();
  clickButton();
  clickButton();
  clickButton();
  clickButton();
  const elements = await screen.findAllByRole("image");
  expect(elements.length).toBe(5); // fails, as it only returns a length of 1
});

How can I get react-testing-library to replicate/add images to the dom rather than replacing them?

I perform tests for 0 images and 1 image and they both pass.

You can see the full code here: https://codesandbox.io/s/bold-bash-cwttx?file=/src/App.js

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I wonder if the problem is with your ClickElement() function.

What if they are not selecting the proper element.

Two ways to debug is to console.log(buttonElement) or just use a different selector, e.g. CSS ID:

const clickButton = () => {
  const buttonElement = screen.getById("YOUR_BUTTON_ID");
  fireEvent.click(buttonElement);
};

Untested

about 4 years ago · Juan Pablo Isaza Denunciar
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