如何测试useState和useEffect React钩子

时间:2019-05-09 14:26:03

标签: javascript reactjs react-hooks

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

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

2 个答案:

答案 0 :(得分:1)

酶目前不支持钩子。我会看Kent C. Dodd的react-testing-library来测试您的Hook。您将测试挂钩的结果,而不是单元测试挂钩本身。

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

答案 1 :(得分:0)

尝试使用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