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

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