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

时间:2019-06-16 13:57:22

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

尝试模拟对API的GET请求,但始终获取

  

超时-在jest.setTimeout指定的10000ms超时内未调用异步回调。

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

挂钩

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);

1 个答案:

答案 0 :(得分:1)

我终于解决了问题。有一种新的方式来编写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