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

437
Vistas
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
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