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

151
Visualizações
React test conditional rendering using the useState hook based on API response

I have this React component that has a block that renders based on an API response.

const SomeComponent = () => {

const [render, setRender] = useState(false)

const handleClick = async () => {
  const someFunction = await callToAPI()
    if (someFunction) {
      setRender(true)
    }
}

return (
  <main>
    <button onClick={handleClick}></button>
    <ShouldRender when={render} data-test-id='should-render'>
      Something
    </ShouldRender>
  </main>
  )
}

As I'm writing the test for it, I'm confused on how to test this conditional rendering. I'd like to know if there's a way to use something like the fireEvent to set this state in my SomeComponent.test.js file.

So far the test looks like this:

test('renders component when button is clicked', () => {
  render(<SomeComponent />)
  const button = screen.queryByRole('button')
  fireEvent.click(button)
  const conditionalComponent = screen.getByTestId('should-render')
  expect(conditionalComponent).toBeInTheDocument()
})
about 4 years ago · Juan Pablo Isaza
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