I have a series of functions, each performing various firestore interactions. How do I use Jest to mock these firestore calls? I would like to avoid using a library.
When I use jest.mock("firebase/app")
and jest.mock("firebase/firestore")
and other variations, I either get null TypeErrors, or errors indicating I am still referencing the actual import and not the mock: Error: ... make sure you call initializeApp()
.
For example, a simple function I want to test:
import firebase from "firebase/app";
import "firebase/firestore";
export const setDocData = (id, data) => {
const newDoc = {
created: firebase.firestore.FieldValue.serverTimestamp(),
...data
};
firebase
.firestore()
.doc("docs/" + id)
.set(newDoc);
};
Notice how firebase is imported as usual, then firestore is imported a side effect. Also notice how firestore is called first as a function, then later referenced as a property. I believe this is the source of my trouble.
I am using
firebase.firestore.FieldValue.serverTimestamp()
in one of my functions:To mock this, I have a jest.setup.js file which I reference in my package.json:
And in jest.setup.js I do:
It's been a while since any activity on this question, but still there's not much material online, here's my solution:
And here's an example usage:
If there is any interest out there I'm fine with packaging the
FirestoreMock
implementation so that it can be easily sharedTeo
Here is the solution I have found. There isn't much information online about this, so I hope it helps someone.
The trick is to create a chained API of mock functions, and set this on the firebase object, instead of importing and mocking firestore. The example below allows me to test the above example function, and also
doc().get()
promises.I declare it in a file that runs before all my tests do (see docs), and import and use it in my test files like this:
Here is how i mocked firebase for jest.
If mocking seems tedious, don't. Use the emulators.
I believe this is a relatively new option for handling reads & writes in testing, so I'm posting it. Here's a quick walk-through.
For an emulator walkthrough guide from Google: https://google.dev/pathways/firebase-emulators
Docs: https://firebase.google.com/docs/emulator-suite
I found that mocking the import works well. I added this code in the test, above where I render my component importing 'firebase/app'