En mi aplicación React, tengo un botón en la pantalla que, después de hacer clic en él, desaparecerá un elemento específico de la pantalla. Al hacer clic en el botón, cambiará un estado y, después de volver a renderizar el componente, el elemento desaparecerá.
Para probar este escenario, estoy usando la biblioteca React Testing . No funciona realmente por waitForElementToBeRemoved :
//element to hide const listContainer = screen.getByRole('list'); //Toggle button const queryButton = screen.getByRole('button', { name: 'Query', }) userEvent.click(queryButton); //this line get error: Exceeded timeout of 20000 ms for a test. await waitForElementToBeRemoved(() => listContainer);pero cuando cambio esperando el proceso funciona:
await waitFor(() => { expect(listContainer).not.toBeInTheDocument(); });no entiendo porque ¿Alguien puede ayudarme?
Cambie su prueba para usar:
//Toggle button const queryButton = screen.getByRole('button', { name: 'Query', }) userEvent.click(queryButton); // Use queryByRole instead of getByRole await waitForElementToBeRemoved(() => screen.queryByRole('list')); Esto debería funcionar ya que queryByRole devuelve un valor nulo en lugar de un error si no se encuentra un elemento. waitFor funciona mientras reintenta hasta que la función envuelta deja de arrojar un error (que es lo que hace getByRole si no se encuentra un elemento). Si el cambio de queryByRole aún no funciona para usted, puede intentar incrementar el tiempo de espera, por ejemplo await waitForElementToBeRemoved(() => screen.queryByRole('list'), {timeout: 3000);
Puede encontrar más información sobre la diferencia entre waitForElementToBeRemoved y waitFor aquí . Consulte también este artículo que aconseja usar solo queryBy... siempre que necesite verificar la inexistencia de un elemento.