javascript - 使用 react-hooks-testing-library 在 React Hooks 中模拟 Axios

标签 javascript reactjs axios react-hooks react-hooks-testing-library

尝试模拟对 API 的 GET 请求但总是得到

Timeout - Async callback was not invoked within the 10000ms timeout specified by jest.setTimeout.

即使我增加了超时时间,它仍然会抛出错误。

Hook

export default function apiCaller() {
  const [rawApiData, setRawApiData] = useState({});
  const [errorMsg, setErrorMsg] = useState('');

  const callApi = async (inputValue) => {
    try {
      const apiData= await axios.get(
        `https://cloud.iexapis.com/stable/stock/market/batch?types=chart&symbols=${inputValue}&range=3m&token=lalaccf0`
      );
      setRawApiData(apiData);
    } catch (err) {
      setErrorMsg(
        'Error occured!! ' +
          (Boolean(err.response) ? err.response.data : err.message)
      );
    }
  };

  return { rawApiData, callApi, errorMsg };
}

Axios 模拟

export default {
  get: jest.fn().mockResolvedValue({ data: {} }),
};

测试

import { renderHook, act } from 'react-hooks-testing-library';
import apiCaller from '../components/stock-chart/stockApiCaller';
import axios from 'axios';
jest.mock('axios');

it('should set error properly when api call is unsuccessfull because of bad data', async () => {

      axios.get.mockResolvedValueOnce({ data: { test: '123' } });
      const { result, waitForNextUpdate } = renderHook(() => apiCaller());

      act(() => result.current.callApi('fb/tsla'));
      await waitForNextUpdate();

      expect(result.current.rawApiData.data.test)
        .toBe(123)
    }, 10000);

最佳答案

我终于解决了这个问题。有一种编写 act() 的新方法,即异步 act()。请在下面找到可以正常工作的更新版本的测试。

it('should set rawData properly when api call is successfull because of', async () => {
  axios.get.mockResolvedValueOnce({ data: { test: '123' } });
  const { result, waitForNextUpdate } = renderHook(() => apiCaller());
  await act(async () => {
    result.current.callApi('fb/tsla');
    await waitForNextUpdate();
  });
  expect(result.current.rawApiData.data.test).toBe('123');
});

更新响应 16.9.0-alpha.0

https://github.com/facebook/react/releases/tag/v16.9.0-alpha.0

关于javascript - 使用 react-hooks-testing-library 在 React Hooks 中模拟 Axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56619497/

相关文章:

javascript - 如何通过@input 属性应用样式,我想增加 mat-autocomplete 的宽度

javascript - 对象数组内的重复条目 : Javascript

javascript - React 在单击时访问列表组件的属性

javascript - CORS '*' 似乎不适用于 Chrome,但适用于 Postman

javascript - Vuex 中如何访问 mapState 并渲染到 View

javascript - 发出多个 ajax 请求来填充表格行。如何对表格列进行排序?

javascript - 在 javascript 中设置后台计时器

javascript - 为什么作为函数参数的内联解构不能按预期工作

javascript - 使用 Dragula Drag and Drop 保存拖动项目的位置,React 版本 (react-dragula)

javascript - 用 Jest 模拟 axios 404?