【问题标题】:Jest - mock function runs but .toHaveBeenCalledTimes() stays 0开玩笑 - 模拟函数运行但 .toHaveBeenCalledTimes() 保持为 0
【发布时间】:2020-08-06 13:06:48
【问题描述】:

我正在尝试测试在调用searchRestaurant 时是否调用了函数searchRestaurantsHelper

问题是接收的次数总是0。

这是测试:

import axios from 'axios';

import Yelp from './Yelp';

import {
  getRestaurantInfoHelper,
  searchRestaurantsHelper,
  searchDefaultRestaurantsHelper,
} from './utils';

jest.mock('./utils.js');
jest.mock('axios');

describe('Testing searchRestaurantsInfo', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });

  test('searchRestaurantsInfo called once and returns something', async () => {
    await Yelp.searchRestaurantsInfo('q_IoMdeM57U70GwqjXxGJw');

    getRestaurantInfoHelper.mockImplementation(() => 'foo');

    expect(getRestaurantInfoHelper).toHaveBeenCalledTimes(1);
    await expect(
      Yelp.searchRestaurantsInfo('q_IoMdeM57U70GwqjXxGJw')
    ).resolves.toEqual('foo');
  });

  test('axios.get called twice', async () => {
    await Yelp.searchRestaurantsInfo('q_IoMdeM57U70GwqjXxGJw');

    expect(axios.get).toHaveBeenCalledTimes(2);
  });

  
});

describe('Testing searchRestaurants', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });

  test('searchRestaurantsHelper called once', async () => {
    axios.get.mockImplementationOnce(() => {
      const response = { data: { businneses: ['foo'] } };
      return Promise.resolve(response);
    });

    searchRestaurantsHelper.mockImplementation(() => 'foo');

    await Yelp.searchRestaurants({
      what: 'tacos',
      where: 'rome',
      sortBy: 'rating',
    });

    expect(searchRestaurantsHelper).toHaveBeenCalledTimes(1);
  });

  test('axios.get called once', async () => {
    await Yelp.searchRestaurants({
      what: 'tacos',
      where: 'rome',
      sortBy: 'rating',
    });

    expect(axios.get).toHaveBeenCalledTimes(1);
  });

 
});

我创建了一个 axios 模拟,因为如果 response.data.businesses.length === 0searchRestaurants 将不会运行 searchRestaurantsHelper。 然后我为searchRestaurantsHelper 创建了一个模拟函数,但显然它没有被调用。

这里是 searchRestaurants()

const Yelp = {
  // Returns restaurant search resuts

  async searchRestaurants(text) {
    try {
      let response = await axios.get(
        `https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/businesses/search?limit=12&term=${text.what}&location=${text.where}&sort_by=${text.sortBy}`,
        {
          headers: {
            Authorization: `Bearer ${YELP_API_KEY}`,
            'X-Requested-With': 'XMLHttpRequest',
            'Access-Control-Allow-Origin': '*',
          },
        }
      );

      if (response.data.businesses.length === 0) {
        return [];
      }

      return searchRestaurantsHelper(response);
    } catch (e) {
      console.log(e);
    }
  },
}

和'./utils'中的searchRestaurantsHelper()

export const searchRestaurantsHelper = (response) =>
  response.data.businesses.map((business) => {
    return {
      id: business.id,
      image: business.image_url,
      name: business.name,
      url: business.url,
      price: business.price,
      phone: business.phone,
      categories: business.categories[0].title,
      address: business.location.display_address[0],
    };
  });

谁能向我解释我做错了什么?我已经卡了一段时间了... 感谢您的帮助!

【问题讨论】:

  • 请为您的问题提供stackoverflow.com/help/mcve。不要截断导入或其他与模块相关的部分,因为它们是相关的。尚不清楚 searchRestaurantsHelper 位于哪个模块中,以及它是如何被模拟的。您描述的问题表明未使用模拟函数,否则断言将通过。
  • 因为 searchRestaurants 不会运行 searchRestaurantsHelper if response.data.businesses.length === 0 - 你不能确定这一点,因为你没有断言Yelp.searchRestaurants 返回的结果,这对于测试来说是一种不好的做法。对于初学者来说,businneses 在一个地方,businesses 在另一个地方。
  • @EstusFlask 我已经包含了导入和模块相关的部分。您建议的问题是拼写错误businneses/```business```。一旦确定测试通过。

标签: javascript reactjs unit-testing testing jestjs


【解决方案1】:

要让jest 跟踪函数调用,您必须spyOn 这个函数,如下所示:

const searchRestaurantsHelper = jest.spyOn(
    searchRestaurantsHelper, 'searchRestaurantsHelper');

这些名称具有误导性,因为您从同名组件中导入了一个函数。为了避免这种情况,你可以重命名你的组件,即以大写开头,也可以重命名你的间谍,即searchRestaurantsHelperSpy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    相关资源
    最近更新 更多