如何测试 useState 和 useEffect 反应挂钩

How to test useState and useEffect react hooks

我正在尝试使用 Jest + Enzyme 测试 useState 和 useEffect 反应钩子,但我找不到方法,有人可以帮忙吗?

const [sPlaceholder, setSPlaceholder] = useState('');
  useEffect(() => {
    setSPlaceholder('abcd');
    if (s === '') {
      dispatchUpdateSPlaceholder(searchPlaceholder);
    }
  }, [sPlaceholder]);

Enzyme 目前不支持 Hooks。我会看看 Kent C. Dodd 的 react-testing-library 来测试你的 Hooks。您将测试 Hooks 的结果,而不是对 Hooks 本身进行单元测试。

https://github.com/testing-library/react-testing-library

尝试使用 act():

import { act } from 'react-dom/test-utils';
act(() => {
  //your condition to update sPlaceholder goes here
});

https://reactjs.org/blog/2019/02/06/react-v16.8.0.html#testing-hooks