Javascript axios模拟适配器应出现错误

Javascript axios模拟适配器应出现错误,javascript,jestjs,axios,axios-mock-adapter,Javascript,Jestjs,Axios,Axios Mock Adapter,我正在尝试使用axios mock adapter测试axios get请求,如果状态不等于200,则会抛出错误。但是,当我执行测试时(请参见api.test.js),我得到以下消息: 错误:expect(函数).tothrower(未定义) 预期函数会引发错误。但它没有扔任何东西 如何使用我的get和handleResponse方法,使用axios模拟适配器进行测试以确保抛出错误?谢谢 api.test.js: import axios from 'axios'; import MockAda

我正在尝试使用
axios mock adapter
测试axios get请求,如果状态不等于200,则会抛出错误。但是,当我执行测试时(请参见
api.test.js
),我得到以下消息:

错误:expect(函数).tothrower(未定义)

预期函数会引发错误。但它没有扔任何东西

如何使用我的
get
handleResponse
方法,使用
axios模拟适配器
进行测试以确保抛出错误?谢谢

api.test.js:

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

const handleResponse = (response) => {
  if (response.status !== 200) {
    throw new Error('foo');
  } else {
    return response.data;
  }
};

const get = async (url) => {
  const response = await axios.get(url, {withCredentials: true});
  return handleResponse(response);
};

test('testing that, when making a get request to the appropriate url, an error is thrown ' +
     ' when status !== 200', async () => {
  new MockAdapter(axios)
    .onGet('sampleUrl')
    .reply(500, {data: 'payload'});
  const expectedError = async () => {
    await get('sampleUrl');
  };
  expect(expectedError).toThrowError();
});

我在您的代码中看到的问题是
expect()。tothrowerr()
需要一个同步异常,但您的代码实际上拒绝了一个承诺。可能令人困惑的是,您看到
抛出新错误('foo')HandlerResponse
中选择code>。这是个例外,没错。但是,由于此代码由
async
函数调用,因此此异常将转换为承诺拒绝。因此,
wait-get('sampleUrl')
不会导致抛出同步异常,而是导致异步承诺拒绝

看看Jest's,我觉得你应该做:

return expect(expectedError()).rejects.toThrowError();
您需要调用
expectedError
,因为它是一个返回承诺的函数,您需要使用
.rejects
将拒绝转换为可使用
.TothRower()测试的普通异常。确保返回断言,或等待它。否则你会有悬而未决的承诺