【发布时间】:2020-11-24 16:02:06
【问题描述】:
我是测试新手,我正在尝试找到一种使用异步函数引发错误的方法。
这是测试文件
import Yelp from './Yelp';
import axios from 'axios';
jest.mock('axios');
describe('testing searchRestaurantsInfo', () => {
// Other tests
test('returns error', async () => {
await expect(
Yelp.searchRestaurantsInfo('q_IoMdeM57U70GwqjXxGJw')
).rejects.toThrow('Error');
});
});
我得到了错误
testing searchRestaurantsInfo › returns error
expect(received).rejects.toThrow()
Received promise resolved instead of rejected
Resolved to value: "Error"
102 |
103 | test('returns error', async () => {
> 104 | await expect(
| ^
105 | Yelp.searchRestaurantsInfo('q_IoMdeM57U70GwqjXxGJw')
106 | ).rejects.toThrow(TypeError);
107 | });
这里是 Yelp.js
import axios from 'axios';
let YELP_API_KEY = process.env.REACT_APP_YELP_API_KEY;
const Yelp = {
// Provides info about a single restaurant
async searchRestaurantsInfo(id) {
try {
let response = await axios.get(
`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/${id}`,
{
headers: {
Authorization: `Bearer ${YELP_API_KEY}`,
'X-Requested-With': 'XMLHttpRequest',
'Access-Control-Allow-Origin': '*',
},
}
);
let responseRew = await axios.get(
`https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/${id}/reviews`,
{
headers: {
Authorization: `Bearer ${YELP_API_KEY}`,
'X-Requested-With': 'XMLHttpRequest',
'Access-Control-Allow-Origin': '*',
},
}
);
const parameters = {
name: response.data.name,
address: response.data.location.display_address[0],
coordinates: {
lat: response.data.coordinates.latitude,
lng: response.data.coordinates.longitude,
},
city: response.data.location.display_address[1],
rating: response.data.rating,
photos: response.data.photos,
phone: response.data.phone,
price: response.data.price,
categories: response.data.categories[0].title,
url: response.data.url,
reviews: responseRew.data.reviews,
};
return parameters;
} catch (e) {
console.log(e);
return 'Error';
}
},
}
我一直在寻找解决方案,实际上我想出的解决方案来自这里:Can you write async tests that expect toThrow? 但它对我不起作用,我不明白我做错了什么。
感谢您的帮助!
【问题讨论】:
-
这与您上一个问题的评论直接相关。如果您希望抛出错误,请不要捕获它。
标签: reactjs unit-testing testing jestjs try-catch