In this tutorial, I will share some code with you that checks that some content exists within a div element with a specific class name. The main reason I've written this tutorial is because I've wasted the last two hours trying to write a test and completely forgot the syntax ๐Ÿ˜‰ For the readers who just want to get straight to the code, then here you go:

Some of the useful things to note about the above. First, on Line 15 I am using the .html() method on the returned mount/shallow component. This can be used to test tghe rendered HTML of a ReactJS component. If you do not use html() your tests will be called against a JSON object that defines the components properties.

Om Line9 I use shallow() to mount the component. There are two ways of mounting a component shallow() and mount(), which one is better? Use mount() when you need to test the component, its events and child components. mount() takes longer to run than shallow is it is processing more things. shallow() doesnโ€™t descend down to sub-components and can be used for quick UI tests. In this example, I only have a single component and nothing nested so shallow() is ideal

Again on Line14, I use find() to search for elements in your HTML. Normal CSS selectors work here!

I will leave you with some useful testing tips. The main coding offences that will make your React components harder to test are:

  • Massive, monolithic objects being passed in. This results in mocking more code than you need to. When you pass a prop into a component, doublethink if you can simplify the amount of data being passed in.

  • Components that do too many things. Try to make a component do one single thing. use the higher-order component pattern to fix this. You can tell when a component is doing too much when your unit tests end up being longer than 20 lines of code. In these instances, try and make your component smaller somehow.

  • Lastly, I would recommend you bookmark these two shortcut pages, which can be very helpful: Jest, Enzyme

Happy Coding ๐Ÿค˜