• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

135
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

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda