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?.