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

220
Views
Node.js y Jest: probando el bucle de promesa, cuente cuántas veces se ha llamado a la función

Quiero probar mi código usando JEST, pero tengo algunos problemas. Quiero verificar si se ha llamado a la función de restart() .

Mi código funciona así, está esperando los datos y, si no hay datos, vuelve a llamar a la misma función. Básicamente algo así como un bucle.

archivo myCode.js:

 module.exports = { getSomething: async () => { return new Promise((resolve, reject) => { setTimeout(() => { resolve(""); }, 1000); }); }, doSomething: async () => { const data = await module.exports.getSomething(); if (!data) { return module.exports.restart(); } return data; }, restart: async () => { return module.exports.doSomething(); } };

archivo myCode.test.js:

 const myCode = require("./exampleCode") describe("test", () => { test("Is it doing something more than once?", async () => { const restartSpy = jest.spyOn(myCode, 'restart'); myCode.doSomething() expect(restartSpy).toHaveBeenCalledTimes(1); }) })

Mi problema es que expect(restartSpy).toHaveBeenCalledTimes(1); está devolviendo falso.

La pregunta es: ¿qué estoy haciendo mal? ¿Hay alguna manera de probar este código?

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

0

El problema principal aquí es la falta de await antes de myCode.doSomething() . Todas sus funciones son asíncronas, por lo que debe esperar a que finalicen antes de verificar el espía:

 await myCode.doSomething();

Otro problema es el hecho de que se trata de un ciclo de recurrencia infinito: jest se agotará después de 5000 ms (de forma predeterminada) si no modifica el código que llama a restart , por ejemplo:

 doSomething: async (restartCounter = 0) => { const data = await module.exports.getSomething(); if (!data && ++restartCounter < 2) { return module.exports.restart(restartCounter); } return data; }, restart: async (restartCounter) => { return module.exports.doSomething(restartCounter); }
about 4 years ago · Juan Pablo Isaza Report

0

En realidad, he encontrado una solución.

 describe("test", () => { test("Is it doing something more than once?", async () => { myCode.restart = jest.fn() const restartSpy = jest.spyOn(myCode, 'restart'); await myCode.doSomething() expect(restartSpy).toHaveBeenCalledTimes(1); }) })

Estoy sobrescribiendo la función de restart() . Así que ahora, puedo agregar la función await to doSomething() y ya no será un bucle infinito. Ahora puedo comprobar si se ha llamado a la función de reinicio

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!