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

436
Visualizações
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 à 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