首页 > 解决方案 > 处理 http 测试请求中的错误

问题描述

我正在使用 jest 来测试我的代码:

export const getReq = async () => {
  let data = '';
  await fetch(
    'https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits',
  )
    .then((response) => {
      let status = null;
      if (response.status === 200) {
        status = response.status;
      } else {
        status = 'error';
      }
      if (status === 200) {
        alert('success');
      } else {
        data = '';
        alert('Error');
      }
      return response.json();
    })
    .then((commits) => {
      data = commits.map(({ sha }: any) => sha)[0];
    });
  return data;
};

现在我想测试我的警报中应该出现的情况: alert('Error');data = '';。所以,为此我创建了这个测试:

test('Asynchronous return values error', async() => {
  global.alert = jest.fn();
  global.fetch = jest.fn().mockResolvedValueOnce({
    json: () =>
        Promise.reject(new Error('my error')),
    status: 401,
  });

  const result = await getReq();

  expect(global.alert).toHaveBeenCalledWith('Error');
  expect(global.fetch).toHaveBeenCalledWith(
      'https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits',
  );
  expect(result).toEqual('');
});

但是当我运行测试时,我得到:Error: my error我的测试不起作用
可能是什么问题以及如何测试我上面描述的东西?

标签: javascriptjestjs

解决方案


推荐阅读