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' }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!
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); });