2

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

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

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

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

1 回答 1

1

我终于解决了这个问题。有一种编写act() 的新方法,即async 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

于 2019-06-16T15:28:14.533 回答