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

435
Views
how to unit test react conditonal rendering comonents

I have started learning unit testing in React. I am implementing a simple API call that renders the person's name stored inside the data State.

import React,{useState,useEffect} from 'react'
import {Props} from '../../Props/Person.props'
import {REACT_APP_CDA_TOKEN,REACT_APP_SPACE_ID,query} from '../../Constants/Query/Person'
export const NameComp = () => {
  
  const [data,setData]=useState<Props | null>(null);
  
  useEffect(()=>{
    window.fetch(
    `https://graphql.contentful.com/content/v1/spaces/${REACT_APP_SPACE_ID}`,
    {
      method:"POST",
      headers:{
        'content-type':'application/json',
        Authorization:`Bearer ${REACT_APP_CDA_TOKEN}`
      },
      body:JSON.stringify({query}),
    }).then((response)=>response.json())
    .then((json)=>setData(json.data))

  },[])
  return (
    !data ? <div>Loading...</div>: <div>
    <p className='name'>{data.person.name}</p>
    </div>  
  )
}

I am unit testing it with the following code.

import React from 'react'
import {shallow} from 'enzyme';
import { NameComp } from '../components/NameComp/NameComp';
describe('Renders Name Component', () => { 
  let container:any;
  beforeEach(() => {
    container= shallow(<NameComp/>)
  })
  it('renders a div',() => {
    expect(container.find('div').length).toEqual(1);
  })
  it('renders a paragraph for name',() => {
    expect(container.contains('p')).toEqual(true)
  })
 })

But the end case is failing because the loading div gets rendered when data is null. How to do testing of such scenario.

also, what is the best way to learn unit-testing in React?.

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!