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

102
Vistas
Bromear el rechazo de la promesa para hacer cumplir el rechazo en la función de llamada

Estoy tratando de probar la siguiente función de get usando Jest. ¿Cómo puedo probar/simular el rechazo de Promise en localForage.getItem , para poder probar el bloque get catch ?

 async get<T>(key: string): Promise<T | null> { if (!key) { return Promise.reject(new Error('There is no key to get!')); } try { return await this.localForage.getItem(key); } catch (err) { throw new Error('The key (' + key + ") isn't accessible."); } }

Intenté lo siguiente:

 test('test get promise rejection', async () => { const expectedError = new Error( 'The key (' + 'fghgdfghfghfdh' + ") isn't accessible." ); jest.fn(localforage.getItem).mockRejectedValue(new Error()); expect(get('fghgdfghfghfdh')).rejects.toThrow(expectedError); });

Pero me sale el siguiente error:

 node:internal/process/promises:246 triggerUncaughtException(err, true /* fromPromise */); ^ [UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "Error: expect(received).rejects.toThrow() Received promise resolved instead of rejected Resolved to value: null".] { code: 'ERR_UNHANDLED_REJECTION' }
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Bueno... eliminamos la palabra clave await de esta línea

 expect(await get('fghgdfghfghfdh')).rejects.toThrow(expectedError);

Porque el error dice claramente

el valor recibido debe ser una promesa o una función que devuelva una promesa

Entonces la prueba falla porque se esperaba que fuera rechazada e inst se resuelve con valor null

Entonces, invoque get sin una clave

 expect(get()).rejects.toThrow(expectedError);

O hacer que la función get sea más defensiva como esta

 async get<T>(key: string): Promise<T | null> { if (!key) { return Promise.reject(new Error('There is no key to get!')); } try { const result = await this.localForage.getItem(key); if (result) return result; throw new Error('empty value'); } catch (err) { throw new Error('The key (' + key + ") isn't accessible: "); } }

¿Qué enfoque usar? Creo que ambos ... de todos modos, ¡espero que te las arregles con tus pruebas!

about 4 years ago · Juan Pablo Isaza Denunciar

0

Lo hice funcionar, tuve que reemplazar localforage.getItem con jest.fn().mockRejectedValue :

 test('test get promise rejection', async () => { localforage.getItem = jest.fn().mockRejectedValue(new Error()); const expectedError = new Error( 'The key (' + 'fghgdfghfghfdh' + ") isn't accessible." ); expect(handler.get('fghgdfghfghfdh')).rejects.toThrow(expectedError); });
about 4 years ago · Juan Pablo Isaza Denunciar
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