Kannan Thayumanavan
Kannan Thayumanavan

Reputation: 63

How to test useState and useEffect react hooks

I'm trying to test useState and useEffect react hooks using Jest + Enzyme, but I can't find a way to do it, can someone please help?

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

Upvotes: 4

Views: 2923

Answers (2)

maxplak
maxplak

Reputation: 11

try to use 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

Upvotes: 1

Katia Wheeler
Katia Wheeler

Reputation: 549

Enzyme currently doesn't support Hooks. I would look at Kent C. Dodd's react-testing-library to test your Hooks. You'll be testing the outcome of the Hooks rather than unit testing the Hooks themselves.

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

Upvotes: 3

Related Questions