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

112
Views
Haga clic en el botón React-testing-library reemplazando elementos dom en lugar de replicarlos

Tengo una aplicación simple que llama a una API y agrega una imagen al DOM al hacer clic:

 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} /> ))} </> ); };

Sin embargo, cuando pruebo esto en la biblioteca de pruebas de reacción y disparo el clic incluso cinco veces, todavía termino con una imagen en el 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 });

¿Cómo puedo obtener react-testing-library para replicar/agregar imágenes al dom en lugar de reemplazarlas?

Realizo pruebas para 0 imágenes y 1 imagen y ambas pasan.

Puede ver el código completo aquí: https://codesandbox.io/s/bold-bash-cwttx?file=/src/App.js

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Me pregunto si el problema está en su función ClickElement() .

¿Qué pasa si no están seleccionando el elemento adecuado?

Dos formas de depurar son console.log(buttonElement) o simplemente usar un selector diferente, por ejemplo, CSS ID:

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

no probado

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!