reactjs - 在 Jest 中测试 Axios

标签 reactjs unit-testing jestjs axios

我是测试新手。 我正在尝试测试一个异步数据获取功能,但我无法弄清楚为什么测试没有通过。 我 Jest mock 了Axios,并给了Axios的get方法一个模拟实现来解决一个 promise 。 该错误表明它无法读取 name 的属性,这意味着我认为数据 obj 未定义。

这是 Yelp.test.js

import Yelp from './Yelp';
import axios from 'axios';

jest.mock('axios');

describe('searchRestaurantsInfo', () => {
  test('returns object with restaurant infos', async () => {
    const data = {
      name: 'Casa Romana',
      address: '5 Albion Street',
      coordinates: { lat: 52.6322649, lng: -1.1314474 },
      city: 'Leicester LE1 6GD',
      rating: 4.5,
      photos: [
        'https://s3-media1.fl.yelpcdn.com/bphoto/4VUq4j1FF-n5bgXjtoC0Xw/o.jpg',
        'https://s3-media1.fl.yelpcdn.com/bphoto/4VUq4j1FF-n5bgXjtoC0Xw/o.jpg',
        'https://s3-media1.fl.yelpcdn.com/bphoto/4VUq4j1FF-n5bgXjtoC0Xw/o.jpg',
      ],
      phone: '+441162541174',
      price: '£££',
      categories: 'Italian',
      url:
        'https://www.yelp.com/biz/casa-romana-leicester?adjust_creative=7GHt4FY-2vjNyIPhQV7wcw&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_lookup&utm',
      reviews: [
        {
          id: 'i_Q39aN9hwZzGDUb-IWpYw',
          rating: 5,
          text:
            'Proper Italian restaurant. Not Italian-themed, or serving Italian fusion cuisine, just a place with an Italian owner who makes solid, straightforward...',
          time_created: '2014-10-02 03:49:36',
          url:
            'https://www.yelp.com/biz/casa-romana-leicester?adjust_creative=7GHt4FY-2vjNyIPhQV7wcw&hrid=i_Q39aN9hwZzGDUb-IWpYw&utm_campaign=yelp_api_v3&utm_me',
          user: {
            id: '6tPD46XZSFllvgn2vTh51A',
            image_url:
              'https://s3-media3.fl.yelpcdn.com/photo/A4Ww6Ks2P9WsALqOFy9cOA/o.jpg',
            name: 'Espana S.',
            profile_url:
              'https://www.yelp.com/user_details?userid=6tPD46XZSFllvgn2vTh51A',
          },
        },
      ],
    };

    axios.get.mockImplementationOnce(() => Promise.resolve(data));

    await expect(
      Yelp.searchRestaurantsInfo('q_IoMdeM57U70GwqjXxGJw')
    ).resolves.toEqual(data);
  });
});

和 Yelp.js

import axios from 'axios';

let YELP_API_KEY = process.env.REACT_APP_YELP_API_KEY;

const Yelp = {
   // Provides infos 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,
      };
      console.log({ parameters, id });

      return parameters;
    } catch (e) {
      console.log(e);
      return e;
    }
  }}

我得到的错误是

searchRestaurantsInfo
    × returns array of restaurnats obj (66ms)

  ● searchRestaurantsInfo › returns array of restaurnats obj

    expect(received).resolves.toEqual(expected) // deep equality

    - Expected
    + Received

    - Object // data object. I removed it from this error message because too long
    + [TypeError: Cannot read property 'name' of undefined]

      47 |     await expect(
      48 |       Yelp.searchRestaurantsInfo('q_IoMdeM57U70GwqjXxGJw')
    > 49 |     ).resolves.toEqual(data);
         |                ^
      50 |   });
      51 | });
      52 | 

      at Object.toEqual (node_modules/react-scripts/node_modules/expect/build/index.js:202:20)
      at Object.<anonymous> (src/helpers/Yelp.test.js:49:16)

  console.log src/helpers/Yelp.js:91
    TypeError: Cannot read property 'name' of undefined
        at Object.searchRestaurantsInfo (C:\Users\Turi\Desktop\project\RestaurantsRedux\src\helpers\Yelp.js:72:29)
        at processTicksAndRejections (internal/process/task_queues.js:97:5)
        at Object.<anonymous> (C:\Users\Turi\Desktop\project\RestaurantsRedux\src\helpers\Yelp.test.js:47:5)

预先感谢您的帮助!

最佳答案

您等待结果的方式可能有问题(可能是编译问题),尝试这样编写测试。

// note make sure the test() function is async

const result = await Yelp.searchRestaurantsInfo('q_IoMdeM57U70GwqjXxGJw')
      expect(result).toEqual(data);

关于reactjs - 在 Jest 中测试 Axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63243468/

相关文章:

php - 如何使用 PHPUnit 的模拟测试名为 "method()"的方法?

reactjs - 如何更改 Material UI 中的选项卡宽度

html - 如何根据 ANTD 表中选择标签中的值禁用日期选择器

reactjs - 如何在页面加载时调度 redux 操作以在 useEffect 中加载数据

c# - 我应该为参数异常编写测试吗?

typescript - Bazel 抛出 "Module ts-jest in the transform option was not found"的 Jest 测试

reactjs - 接下来js自定义服务器使用express来路由

c# - 测试项目在它正在测试的项目中找不到对象

javascript - JEST 抛出 .finally 不是一个函数

.spec 文件中无法识别 Angular 8+ tsconfig 路径别名