我正在嘗試get使用 Jest測驗以下功能。如何在 中測驗/模擬 Promise 拒絕localForage.getItem,以便我可以測驗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.");
}
}
我嘗試了以下方法:
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);
});
但我收到以下錯誤:
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'
}
uj5u.com熱心網友回復:
好吧...我們await從這一行中洗掉關鍵字
expect(await get('fghgdfghfghfdh')).rejects.toThrow(expectedError);
因為錯誤清楚地表明
收到的值必須是一個承諾或回傳一個承諾的函式
然后測驗失敗,因為它預計會被拒絕并且 insted 是用null值解決的
get所以,要么在沒有密鑰的情況下呼叫
expect(get()).rejects.toThrow(expectedError);
或者get像這樣使功能更具防御性
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: ");
}
}
使用哪種方法?我認為兩者都......無論如何我希望你能通過你的測驗!
uj5u.com熱心網友回復:
我得到了它的作業,我不得不替換localforage.getItem為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);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/417407.html
標籤:
上一篇:C 標準的單元測驗
