I have been trying to test if a title of a simple React component appears as I want, but it makes API requests and I think that’s the reason why I can’t get the page loaded correctly before making the assertions. Following are the component, the test so far and the test’s result:
That’s the component:
const Sobre = () => {
const { jaimeRamirez, error, isLoading } = useJaime()
if (isLoading) return <h1>Carregando...</h1>
if (error) return <div>Erro: {error.message}</div>
return (
<div className="posicao-sobre">
<div className="texto">
<div className="titulo-texto">
<h1 className="quem-sou-eu" id="demo">
Quem sou eu?
</h1>
</div>
<div className="descricao">
<p>
{jaimeRamirez.nombre} é um experiente desenvolvedor React que
compartilha seu vasto conhecimento através de cursos online. Formado
em Engenharia da Computação pela Unisanta (2013), é Team Leader na{' '}
{jaimeRamirez.compania}. Atualmente está atrás de um{' '}
{jaimeRamirez.coche}.
</p>
</div>
</div>
<div className="imagem">
<img src={jaime} alt="jaime" className="jaime" />
</div>
</div>
)
}
export default Sobre```
The custom hook:
import { useQuery } from 'react-query'
import axios from 'axios'
export const retrieveData = async () => {
const response = await axios.get('http://localhost:8080/jaime/')
return response.data
}
export function useJaime() {
const {
data: jaimeRamirez,
error,
isLoading,
} = useQuery('DadosDoJaime', retrieveData)
return { jaimeRamirez, error, isLoading }
}
The test so far:
import React from 'react'
import { render, screen, waitFor } from '@testing-library/react'
import Sobre from '../pages/Sobre'
import { useJaime } from '../pages/Sobre/hooks'
import { QueryClient, QueryClientProvider } from 'react-query'
const queryClient = new QueryClient() // Resolvi sozinho! :D
const resultado = {
data: {
nombre: 'Jaime Ramírez',
compania: 'Microsoft',
coche: 'Porsche',
},
isLoading: false,
error: false,
}
describe('Testando O Componente <Sobre />: ', () => {
test('Se o título aparece: ', async () => {
render(
<QueryClientProvider client={queryClient}>
<Sobre />
</QueryClientProvider>,
)
const titulo = screen.getByText('Quem sou eu?')
await expect(titulo).toBeInTheDocument()
})
})
And the result so far:
I would probably need to mock something, but I’m sure what exactly and neither if that’s the solution.
Thanks in advance,
Douglas
Douglas de Brito is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.