Write test for React: component, hoc, hooks, promise, saga, graphql, custom hooks

In this article, I will talk about writing test for react component, connected component, higher order component(HOC), native react hooks, redux saga function (generator function), and function with promise. In the end, I will also talk about an important technique in react testing: how to mock dependencies.

All the examples are available in this git repo: react test demos

Let’s GO!

1. Test with a component

Imagine that we have a component with the name of “Com” with another component “SubCom” inside. Here is an example of testing the existences of certains elements and the function callbacks from user interactions:

Link to source code.

2. Test with connected component and HOC (Higher Order Component)

In fact, ‘Connect’ in react-redux is a Higher order component. In general, in order to test with Higher order component, we just need to mock the compose in tests.

Here is another example of testing HOC with redux-form.

Link to source code.

3. Test with redux-saga

Link to source code.

4. Test with promise function

Link to source code.

5. Test with react hooks

Link to source code.

6. Test graphql queries

If the query is made by the hook useQuery and if it is used only once in the component, it is not a bad way to mock useQuery to return the expected result. (For more information: How to mock dependencies in jest: the pitfalls, the tricks and the best practices)

7. Test custom hooks

Without a library, it is not easy to test a custom hook independently because it “lives” in a component. Luckily the library react hooks testing library helps us solve this problem.

Let’s take an example of a custom hook which uses two other hooks (useContext and useQuery).

Here is the full working examples. Thanks for reading !

Fun of ReactJS, Javascript, Data visualization www.yuebaixu.com