用 Jest 抛出的异步测试

Posted

技术标签:

【中文标题】用 Jest 抛出的异步测试【英文标题】:Async test to throw with Jest 【发布时间】: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? 但它对我不起作用,我不明白我做错了什么。

感谢您的帮助!

【问题讨论】:

这与您上一个问题的评论直接相关。如果您希望抛出错误,请不要捕获它。 【参考方案1】:

假设您在测试中断言 Promise 拒绝之前模拟 axios.get 拒绝,那么在 catch 块中的 Yelp.js 中存在问题。你需要重新抛出错误:

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

如果你还没有模拟 axios 抛出错误,请在调用函数之前添加:

axios.get.mockRejectedValue('error');

如果这对你有用,请告诉我。

【讨论】:

以上是关于用 Jest 抛出的异步测试的主要内容,如果未能解决你的问题,请参考以下文章

开玩笑 - 断言异步函数抛出测试失败

用 jest 测试 redux 异步动作创建者

如何使用 toThrow 和 Jest 断言异步方法抛出错误

如何让 Jest 静默测试抛出的错误

测试异步函数 - JEST

在异步 Jest 测试中是不是需要完成?