Vera
Jun 29, 2022

React Testing

My personal philosophy on testing

A lot of my testing philosophy is based on Kent C dodds teachings so you will see a lot of his sentiments echoed here, but I some of my own thoughts as well.

Many integration tests. No snapshot tests. Few unit tests. Few e to e tests.

Unit testing is step above snapshot testing but its not ideal. It is however much easier to understand and maintain then snapshot testing.

Write mostly integration tests. Unit tests are good but they don't really resemble the way your end user interacts with your app. It is very easy to test implementation details with unit tests, especially with shallow render.  

Integration tests should mock as little as possible

Do not test implementation details such as names of functions and variables.

For example if we are testing a button and change the name of the function in the onClick method from increment() to handleClick() our tests would break but our component will still function. This is bad practice because we are basically just testing the name of the function which is an implementation detail, which our end user does not care about.

Shallow vs 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 and 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.

For example consider this child and parent component.

Osama Megahed

Osama Megahed

this is the first blog to me and I am trying to do my best to make it as better as I can

Leave a Reply

Related Posts

Categories