Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!