Testing React Components with Hooks & Mocks [Full Guide]
FAQ
Why hooks in React are essential for testing?
Because hooks are essential for modern react development they are used in every react project nowadays. Tested hooks save teams from unpredictable bugs.
What are the best practices for testing React components that use hooks?
1. Do not test implementation details of hooks. Test API that hooks provide.
2. Try to avoid using mocks until it is completely necessary.
3. Test hooks in isolation without involving any components.
How do I test a component that uses the useEffect hook in React?
You should not try to mock useEffect (mocking is only needed for Enzyme shallow rendering). Usually you need to wait until async side effects in use effect hooks will be completed. For this purpose i recommend to use waitFor [https://testing-library.com/docs/dom-testing-library/api-async/#waitfor] it will wait for async functions to complete before continuing the code. If you do not have async side effects, waitFor is not needed. In the end of your test you need to use expect to check useEffect impact on the component.
I can't test the React components, can you help me with this?
Yes, I would recommend you to check my article. It has setup instructions for react-testing-library. Also I would recommend checking the documentation of react-testing-library.