Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda