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

119
Views
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 answers
Answer question

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 Report
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!