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