How can I effectively test the get
function in Jest, specifically by mocking Promise rejection in localForage.getItem
to test the catch
block?
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.");
}
}
I attempted the following:
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);
});
However, an error occurs:
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'
}