【发布时间】:2022-01-20 07:26:59
【问题描述】:
我正在尝试使用 Jest 测试以下 get 函数。如何测试/模拟 localForage.getItem 中的 Promise 拒绝,以便我可以测试 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'
}
【问题讨论】:
标签: javascript typescript unit-testing jestjs mocha.js