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?
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); }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