繁体   English   中英

使用 try/catch 测试 useEffect 钩子

[英]Testing of useEffect hook with try/catch

我需要在获取数据请求拒绝时测试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) 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();
});

If I test case when fetchSomething with Promise.resolve() evertyhing works fine and tests are correct but when I try to Promise.reject() in order to test catch case then this error is not catched and I have unhandled promise rejection . (为什么代码看起来像这样:在应用程序的其他地方,我使用 redux 处理状态更改,因此对 catch 的测试很容易,但在一个地方我需要为组件获取 3 个不同的资产,我决定使用useState因为从 redux 中提取 3 个不同的状态并将其组合起来会很丑,我认为useState更干净)

在此先感谢您的帮助::)

我遇到了同样的问题,即在 useEffect() 中使用 try/catch 子句时不起作用。 我做了一些搜索,看来这是一个潜在的错误,请查看:

https://github.com/testing-library/react-hooks-testing-library/issues/305

也就是说,我能够解决以下问题:

失败示例:

useEffect(() => {
  try {
      invokeMyAsyncFunction();  
      setStatus(SUCCESS);
  } catch (e) {
      setStatus(FAILURE);   // <== will not be invoked on exception!!
  }
}

成功案例:

useEffect(() => {
  invokeMyAsyncFunction()
     .then((response:any) => {
        setStatus(SUCCESS);
     })
     .catch((e) => {
        setStatus(FAILURE);   // <== this **WILL** be invoked on exception
     });
}

你需要像这样编写你的catch块:

catch (e) {
     // can do something with e in here
      setStatus(FAILURE);
    }

这很好,您需要在 useEffect 中声明您的 function 并在其中实现 try/catch 块,在 function 之外您只需调用它

(另外,别忘了清理你的使用效果)

    useEffect(() => {
      const fetchAssets = async () => {
        setStatus(IN_PROGRESS);

        try {
          await fetchFirstAsset();
          await fetchSecondAsset()

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

      fetchAssets();
    }, []}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM