Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

438
Views
Probando una función que tiene una Promesa y setTimeout, ¿por qué se agota el tiempo?

Estoy tratando de probar una función que tiene setTimeout dentro de una promesa. Sin embargo, sigue agotando el tiempo.

Esta es la función:

 export const sleep = async (duration: number): Promise<void> => { await new Promise<void>((resolve) => { setTimeout(resolve, duration); }); if (process.env.NODE_ENV === "test") { console.log("sleep end"); } };

Y esta es mi prueba:

 import { sleep } from "../../helpers/utils"; console.log = jest.fn(); jest.useFakeTimers(); test("calls sleep with correct argument and calls console.log", async () => { const NODE_ENV = "test"; const SLEEP_DURATION = "100"; process.env = { ...process.env, NODE_ENV, SLEEP_DURATION }; const timeoutSpy = jest.spyOn(global, "setTimeout"); await sleep(+SLEEP_DURATION); jest.runAllTimers(); expect(sleep).toHaveBeenCalledWith(+SLEEP_DURATION); expect(timeoutSpy).toHaveBeenCalledWith(+SLEEP_DURATION); expect(console.log).toHaveBeenCalledWith("sleep end"); });

El problema es que cuando intento ejecutar esto, la prueba falla y da este mensaje:

 thrown: "Exceeded timeout of 5000 ms for a test. Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."

jest.setTimeout(10000) que arroja un error de Exceeded timeout of 10000ms ...

¿Alguna idea de por qué sucede esto? O como arreglarlo.

¡Gracias!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Aquí hay una solución que se acerca más a lo que está buscando. Es importante destacar que no puede await la resolución de la promesa utilizando temporizadores falsos o nunca se resolverá. En su lugar, puede llamar a asignar el valor de retorno de la función de sleep a una variable, luego ejecutar los temporizadores y luego esperar la variable.

También ajusté su declaración de expect para el espía de tiempo de espera, ya que requiere dos argumentos. Finalmente, eliminé su expectativa de que el sleep se llama con la duración porque literalmente lo está haciendo en la prueba, por lo que no parece que valga la pena hacer esa afirmación.

 console.log = jest.fn(); jest.useFakeTimers(); test("calls sleep with correct argument and calls console.log", async () => { const NODE_ENV = "test"; const SLEEP_DURATION = "100"; process.env = { ...process.env, NODE_ENV, SLEEP_DURATION }; const timeoutSpy = jest.spyOn(global, "setTimeout"); const sleepFn = sleep(+SLEEP_DURATION); jest.runAllTimers(); // Now that we ran timers we can await the promise resolving await sleepFn; // timeout takes two arguments expect(timeoutSpy).toHaveBeenCalledWith( expect.any(Function), +SLEEP_DURATION ); expect(console.log).toHaveBeenCalledWith("sleep end"); });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!