Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

113
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda