What You May Not Know About Jest’s Mount Method
- By : Mydatahack
- Category : Front-End, Web Technologies
- Tags: Front End, Jest, React
If you are a React developer, you probably know the difference between mount and shallow when you are unit testing react components with jest. Mount renders full DOM. We use it when the component interacts with DOM Api or require a full lifecycle to fully test the component. On the other hand, shallow renders only the component you are testing to avoid asserting on the behaviours of child components indirectly. Ok, these are pretty well known facts.
Ok, so if you have a component without a child, do you think both shallow and mount render html the same? The answer is no. They actually render differently. In short, mount renders html wrapped with the component tag while shallow just renders as you expect.
We have a simple component like this.
When we use mount, the div will be rendered as below. This can be console-logged by using .debug().
On the other hand, shallow will render the component as below.
When you assert with mount, you cannot assert without finding the div first. Of course, the correct thing to do here is to use shallow. Mount is not the right method to use for a simple component like this.
There you go. Another minor detail about jest…