用Jest进行异步测试

时间:2020-08-04 14:18:36

标签: reactjs unit-testing testing jestjs try-catch

我是测试的新手,我正在尝试寻找一种使用异步函数引发错误的方法。

这是测试文件

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? 但这对我不起作用,我做错了。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

假设您在测试中声明承诺被拒绝之前嘲笑axios.get拒绝,则Yelp.js中catch块中存在一个问题。您需要重新抛出错误:

catch (e) {
      console.log(e);
      throw e;
}

如果您尚未模拟axios引发错误,请在调用函数之前添加此错误:

axios.get.mockRejectedValue('error');

让我知道这是否对您有用。