Every time I used Firebase, I ran into the problem of how to test Firebaseâs database and authentication. Since I am using Jest as my default testing environment, I figured everything I needed already comes with Jest. In this tutorial, you will learn how to mock Firebaseâs features. We will use Firebase Admin SDK for the Firebase setup, however, the same works with the traditional client-side Firebase using Firebase Real-Time Database, Firebase Firestore, and Firebase Authentication.
After setting up Firebase, we have our first database function which creates a record in Firebaseâs database:
In our test file, a test with Jest could be similar to this one for testing the Firebase function:
Before this test can run through, we need to mock Firebase in the test file to cover the problematic lines (highlighted). Instead of mocking Firebase as library, we mock the setup which happens in another file which I have shown before:
Now itâs possible to call Jestâs toHaveBeenCalledTimes() and toHaveBeenCalledWith() on the mocked function. However, we still didnât mock the Firebase timestamp properly. In our source code, letâs use the explicit Firebase import rather than our Firebase setup for the timestamp:
Now, we can Jest mock the Firebase import for the Firebase constant in our test:
The Firebase constant should be alright in our test assertion now. Also you could consider moving the last Firebase mock into your jest.setup.js file, because it may be needed for other unit and integration tests as well. After all, you should have everything at your hands to test Firebase applications now.