Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
How to write unit testcase using JEST if text shown conditionally with useState

sample.js


const Sample = () => {
    const [show, setShow] = useState(false);
    const onShow = () => {
        setShow(!show);
    }
    return(
        <div>
            <button onClick={onShow}>{show ? 'Hide Text' : 'Show text'}</button>
            {show && <label>Welcome!!</label>}
        </div>
    );
};
export default Sample;

Sample.test.js

import Sample from '../components/sample';
import React from "react";


test('render Sample text matcher', () => {
    render(<Sample />);
    const titleElement = screen.getByText(/Welcome!!/)
    expect(titleElement).toBeInTheDocument;
})

It throw following error. How can I write testcase if element render with state value?

TestingLibraryElementError: Unable to find an element with the text: /Welcome!!/. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

As a workaround, just after rendering you could try to do a click on the button that activate your display :

document.querySelector('button').click();
about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to click on your button first. Otherwise show is false and the text is not displayed.

You can use:

const button = screen.getByRole('button');
fireEvent.click(button); // import this from react-testing-library
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda