In this tutorial, you will find a number of useful code snippets that will help you test various testing scenarios for components written using ReactJS. Examples will range from snapshot testing to mocking. There is a load of good stuff here that will help you on your testing journey.

Snapshop Testing

Snapshot tests are useful to make sure that people don't accidentally break how a component renders after you have finished with it. The first time a snapshot test is run, a folder will be created in the same directory you run the test called __snapshots__. If it runs successfully, you should see a file mirroring your test file except with a .snap file extension. If you open this file within a text editor, you should see a bunch of HTML. This is the basics of snapshot testing. The test framework will compare the HTML and this is how it will know if a component has changed or not!

After you have updated your JSX, you may find that your snapshot test will fail. This should be pretty obvious to understand. You've changed the markup so the final component will now look different. To fix these failures is simple. Create a fresh snapshot, check it in and job done! To update a snapshot, simply run jest with the --updateSnapshot, or, simplified -v flag, e.g. yarn test -u:

Test A Function Has Been Called

Another common test you will likely want to perform is checking that a function has been called when a component has been loaded. One example is that an async request has been made to get some data from an API in your componentMount(). The easiest way to test this is to pass the function in as a prop into the component. In your test, you can then mock the function, pass it in and then use a method like .toHaveBeenCalled() to ensure if was called as expected:

Testing A Prop/Function Inside Your Component Has The Correct Data

In some situations, mocking a few calls might not give you confidence that your component is working as expected. In these situations, you may want to write a more explicit test for certain scenarios. You can test these sort of cases, using the .instance() method, like so:

Testing What Happens When A Prop Updates After Load

You can also update props within a component using setProps():

Checking A Button Click Does What You Want It To

Another common test is to make sure that after a user has clicked on a button, the component does what you expect it to do. You can do this with the .simulate() method, like so:

Filtering What Tests Are Run

If you only want to speed up your development workflow you may want to prevent all tests from running while you are building a component. Waiting for a whole suite of tests to run wastes time. A quicker approach is to only run the specific test you are working on. You can do this by filtering which test are run based on a name:

That concludes my list of shady test snippets. I hope you found some value in the list. Happy Coding 🤘