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

162
Vistas
Change a state value in React Testing Library

Having the following component:

import { useState } from 'react';

export function MyComponent() {
  const [val, setVal] = useState(false);

  return (
    <div>
      big container
      <button onClick={() => setVal(!val)}>click</button>
      {val && <div>small container</div>}
    </div>
  );
}

export default MyComponent;

There is a div containing the text "small container", which only appears when val is true.

I want to write a test in jest for this but don't know how to mock the value of val there

Here is my code so far:

  it('small container visible only when val is true', () => {
    const { queryByText } = render(<MyComponent />);
    const toTest = queryByText('small container');
    expect(toTest).not.toBeInTheDocument();
  });

this test passes, but how can be added val set to true in order to test that toTest is present in the document?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can click the button which will set the val to true.

it('small container visible only when val is true', () => {
  const {queryByText, getByTestId} = render(<MyComponent />);
  const clickButton = getByTestId('your.button.test.id');
  fireEvent.click(clickButton);
  expect(queryByText('small container')).toBeInDocument();
});

React testing library does not recommend to test implementation details as per documented here. That's why you might not want to access internal state of component while testing.

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