In this tutorial, you will find a number of code examples that cover a range of different testing scenarios that I've needed to write for some of the React.js websites I've worked on.
Basic Snapshot Test Example
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 extension. If you open this in a text editor, you should see a bunch of HTML. This is the basics of snapshot testing.
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 correct this is fairly simple. All you need to do is take a fresh snapshot, check it in and job done! Simple! 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
One very common thing you may want to test against is that a function has been called when a component has been loaded. One example is that maybe an async request has been made to get some data from an API in your componentMount(). To do this, the easiest way to test this situation 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()
Testing A Prop/Function Inside Your Component Has The Correct Data
In some situations, just knowing a function is more explicit enough to give you confidence that your component is working as expected. In these situations, you may want to write 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 making 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:
Useful Jest Command Options
Only run a specific test, based on a name:
Update snapshots if needed: