A Short Note – What Is Difference Between Shallow And Mount In React Testing ?

Hello Readers, CoolMonkTechie heartily welcomes you in A Short Note Series.

In this note series, we will discuss about difference between Shallow and Mount in React Testing.

So Let’s begin.

Mount

Mount actually executes the html, css and js code like a browser would, but does so in a simulated way. It is “headless” for example, meaning it doesn’t render or paint anything to a UI, but acts as a simulated web browser and executes the code in the background.

Not spending time painting anything to the UI makes your tests much faster. However mount tests are still much slower than shallow tests.

This is why you unmount or cleanup  the component after each test, because it’s almost a live app and one test will affect another test.

Mount/render is typically used for integration testing.

Shallow

Shallow is used for unit testing. Shallow rendering only renders the single component we are testing. It does not render child components. This allows us to test our component in isolation.

When writing unit tests for React, shallow rendering can be helpful. Shallow rendering lets you render a component “one level deep” and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered. This does not require a DOM.

Conclusion

In this note series, We understood about the difference between Shallow and Mount in React Testing. So we conclude that

  • Shallow() tests components in isolation from the child components they render while mount() goes deeper and tests a component’s children.
  • Mount(<Component />) for Full DOM rendering is ideal for use cases where you have components that may interact with DOM apis, or may require the full lifecycle in order to fully test the component (ie, componentDidMount etc.) while shallow(<Component />) for Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that your tests aren’t indirectly asserting on behavior of child components.
  • Mount/render is typically used for integration testing while Shallow is used for unit testing.

Thanks for reading ! I hope you enjoyed and learned about Shallow and Mount Concepts in React Testing. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Exit mobile version