Jest mock promise rejection 强制拒绝调用函数

Jest mock promise rejection to enforce rejection in calling function

我正在尝试使用 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'
}

嗯...我们从这一行中删除 await 关键字

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

因为错误说的很清楚

received value must be a promise or a function returning a promise

然后测试失败,因为它预计会被拒绝,并且已用 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: ");
  }
}

使用哪种方法?我认为两者都......无论如何我希望你能通过你的测试!

我成功了,我不得不将 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);
});