Behold! The long-awaited third (and final) installation of this saga — testing with Jest!
In the last blog, we covered CRUD with Firebase, so we’re going to continue our CRUD-dy fun with testing this in Jest! This was one of the more exciting pieces of this project for me, since there didn’t appear to be a straightforward way to test the Firebase database and authentication.
After a bit of research, I came across this blog post by Robin Weiruch. While it didn’t cover everything I was looking for, it gave me the confirmation that what I was looking for existed in the Universe. So, between the blog, and the acres of Jest and Firebase documentation, I was able to test all of the Firebase CRUD functionality to my heart’s content. Here’s how it went!
Although it is entirely possible to create a small collection in Firebase and just test CRUD functionality on it, Jest provides an easier way of going about it locally with the firestore-jest-mock dependency. Step 1 is to npm install this dependency to your package.json file.
Once you’ve got the dependency, it’s time to set up a spec file. (E.g. firebase.spec.js or however you name your Jest files) and in that spec file, create a mock firestore.
Once you’ve got that sorted, it’s time to set up a mock Firebase collection to run tests on.
Now you are all set to test some Firebase CRUD operations! (Remember, to test your spec file/s, you’ll need to run npm test in your terminal.)
The syntax for testing a Firebase CRUD operation in Jest is very similar to writing an actual Firebase CRUD operation. Since you’re mocking the database (which Firebase calls “collection”, as a reminder) directly in the Jest file, you can reference it easily, and then just wrap it in a typical Jest test function. Easy peasy. You can put anything you want to check for in the .then() as long as you follow the Jest syntax.
Here, we have two examples of a GET and a GET by ID. The only exciting change here is that to successfully fetch a single ID from a collection, it was most effective to do an async-await.
In hindsight, this all seems pretty cut and dried, but at the time, it took many hours of sad labor to figure out the correct syntax, finding a npm library that worked, and making sure the tests all worked. I enjoyed the learning process, and finding a new way to tinker with React, so I hope to continue trying something else exciting in a new project.
For folks looking for a simple way to a React app nice and CRUD-dy with Firebase, I hope this three-parter was helpful. Feel free to contact me with any feedback or if you need some more info/help with your project!