使用try / catch测试useEffect挂钩

问题描述 投票:0回答:1

我在获取数据请求拒绝时需要测试catch,但我不明白为什么未捕获错误,并且我收到此错误:UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

我有这样的情况:

export const Container = ({fetchFirstAsset, fetchSecondAsset}) => {
  const [status, setStatus] = useState(null);

  async function fetchAssets() {
    setStatus(IN_PROGRESS);

    try {
      await fetchFirstAsset();
      await fetchSecondAsset()

      setStatus(SUCCESS);
    } catch {
      setStatus(FAILURE);
    }
  }

  useEffect(() => {
    fetchAssets();
  }, []);

  ....
};

并像这样测试:

import {mount} from 'enzyme';
import {act} from 'react-dom/test-utils';

const fetchFirstAsset = jest.fn();
const fetchSecondAsset = jest.fn();

it('should render without errors', async () => {
  fetchFirstAsset.mockReturnValueOnce(Promise.resolve());
  fetchSecondAsset.mockReturnValueOnce(Promise.reject());
  let component;

  await act(async () => {
    component = mount(
      <Container
        fetchFirstAsset={fetchFirstAsset}
        fetchSecondAsset={fetchSecondAsset}
      />
    );
  });

  expect(fetchSomething).toHaveBeenCalled();
});

[如果在用fetchSomething解析Promise.resolve()时测试用例,一切都可以正常工作并且测试是正确的,但是当我尝试使用Promise.reject()来测试catch用例时,则不会捕获此错误,并且我有unhandled promise rejection 。(为什么代码看起来像这样:在应用程序的其他地方,我使用redux来处理状态更改,因此对catch的测试很容易,但是在一个地方,我需要为组件获取3种不同的资产,因此我决定使用useState,因为从redux中提取3种不同的状态并将其组合起来会很丑陋,我认为useState会更干净)]

谢谢您的帮助! :)

reactjs react-hooks enzyme jest use-effect
1个回答
0
投票

您需要这样编写catch块:

catch (e) {
     // can do something with e in here
      setStatus(FAILURE);
    }
© www.soinside.com 2019 - 2024. All rights reserved.