我正在尝试使用 测试 axios get 请求axios-mock-adapter
,从而在状态不等于 200 的情况下引发错误。但是,当我执行测试时(请参阅api.test.js
),我收到以下消息:
错误:expect(function).toThrowError(undefined)
期望函数抛出错误。但它没有扔任何东西。
如何axios-mock-adapter
使用 myget
和handleResponse
方法进行测试以确保引发错误?谢谢!
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();
});