Tengo un componente React ComponentA que una vez que se procesa, inicia la función setTimeout para retrasar 500 ms y luego renderiza el texto principal. Necesito probar que durante estos 500ms no aparece el texto principal y no pude averiguar cómo.
El componente A:
function ComponentA() { const [showIndicator, setShowIndicator] = useState(false); useEffect(()=> { setTimeout(()=> setShowIndicator(true), 500); }) return (showIndicator && <h1>Hello</h1>); }Mi configuración de prueba actual hasta ahora es
import {render} from '@testing-library/react' describe("Test Component A", () => { test("it should not show text during first 500 ms", async () => { // Point A: rendering time const {container, getByText} = render(<ComponentA />) // Point B: before delay // Need to assert text is not shown yet before delay await sleep(500); // Poin C: now text should appear expect(getByText('Hello')).toBeInTheDocument() }); });Está pasando, pero no puedo entender cómo afirmar que el texto no aparece antes de que pasen los 500 ms y cómo saber que el momento en que ocurre la afirmación es antes de los 500 ms. Cualquier ayuda se agradece, gracias
Puede esperar un poco más y verificar que el texto no esté en el documento:
test("it should not show text during first 500 ms", async () => { const {container, getByText} = render(<ComponentA />) await sleep(499); expect(getByText('Hello')).not.toBeInTheDocument() }); Además, no estoy seguro de qué proviene sleep , pero en caso de que se produzca un retraso real , sugiero considerar temporizadores falsos en su lugar:
test("it should not show text during first 500 ms", async () => { const {container, getByText} = render(<ComponentA />) jest.advanceTimersByTime(499); expect(getByText('Hello')).not.toBeInTheDocument() });Y finalmente, puede fusionar 2 casos de prueba juntos (no porque crea que el recuento de casos de prueba importa, sino porque en realidad prueba el mismo aspecto relacionado con el retraso que se muestra antes):
test("shows text after 500 ms delay", async () => { const {container, getByText} = render(<ComponentA />) jest.advanceTimersByTime(499); expect(getByText('Hello')).not.toBeInTheDocument() jest.advanceTimersByTime(2); expect(getByText('Hello')).toBeInTheDocument() });