使用 jest 模拟多个 Axios 调用

时间:2021-04-19 19:44:45

标签: redux-mock-store jest-mock-axios

我在 React 中有这个 async 任务。我使用了 Axios 和 redux-thunk。我想用玩笑写一个测试。但是此 redux doc 中的示例使用了 fetch-mock,它模拟使用 fetch 或 node-fetch 发出的请求。如何实现测试来模拟 Axios?:

const fetchMeals = () => async (dispatch) => {
  dispatch(fetchMealsRequest);
  try {
    const { data: { categories } } = await axios.get('https://www.themealdb.com/api/json/v1/1/categories.php');
    const arrOfPromises = categories.map((cat) => axios.get(`https://www.themealdb.com/api/json/v1/1/filter.php?c=${cat.strCategory}`));
    const allMeals = await Promise.all(arrOfPromises);
    const meals = categories.reduce((acc, currVal, idx) => {
      acc.push({
        mealCategory: currVal.strCategory,
        categoryThumb: currVal.strCategoryThumb,
        categoryDescription: currVal.strCategoryDescription,
        meals: allMeals[idx].data.meals,
      });
      return acc;
    }, []);
    dispatch(fetchMealsSuccess(meals));
  } catch (err) {
    dispatch(fetchMealsFailure(err.message));
  }
};

0 个答案:

没有答案