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

188
Visualizações
Unit testing for Custom hooks with functions that contain setTimout()

The main problem is that I can't seem to get to the next lines of the code because of an await function in my CustomHook. For context, I have created a function called sleep that looks like this.

export const sleep = (ms: number): Promise<void> =>
  new Promise<void>((res) => setTimeout(res, ms));

Now my custom hook looks something like this.

const useCustomHook = () => {
  const [sampleState, setSampleState] = useState(null);

  const callApiFunction = async () => {
    const results = await callApi();
    await sleep(500);
    if(results.success) {
      const secondResults = await callSecondApi();
      await sleep(500); 
      if(secondResults.success) {
        setSampleState(secondResults.data); //Should set state to an {}
      }
    }
  }

  return {
    sampleState, 
    callApiFunction,
  }
}

To create a unit test for this, I'm using @testing-library/react-hooks.

I've written a test where

it('should do something', async () => {
  jest.useFakeTimers()
  const {result, waitForNextUpdate} = renderHook(()=> useCustomHook())
  // Using act since we won't allow running functions that changes states without act
  act(() => {
    result.current.callApiFunction();
    jest.advanceTimersByTime(500);
  })
  await waitForNextUpdate()
  expect(result.current.sampleState).toEqual(expectedApiResults);
})

The ones above are pretty much simplified but its basically the gist. I've seen other implementations but most of them are using useEffect which is a bit different from what I want to do.

Also with he implementation above I get "Exceeded timeout of 5000 ms for a test. Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test." and state is still `null

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