Security News
New Python Packaging Proposal Aims to Solve Phantom Dependency Problem with SBOMs
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.
firestore-jest-mock
Advanced tools
Jest Mock for testing Google Cloud Firestore
A simple way to mock calls to Cloud Firestore, allowing you to assert that you are requesting data correctly.
This is not a pseudo-database -- it is only for testing you are interfacing with firebase/firestore the way you expect.
This library is NOT feature complete with all available methods exposed by Firestore.
Small, easy to grok pull requests are welcome, but please note that there is no official roadmap for making this library fully featured.
This library provides an easy to use mocked version of firestore.
With npm:
npm install --save-dev firestore-jest-mock
With yarn:
yarn add --dev firestore-jest-mock
mockFirebase
The default method to use is mockFirebase
, which returns a jest mock, overwriting firebase
and firebase-admin
. It accepts an object with two pieces:
database
-- A mock of your collectionscurrentUser
-- (optional) overwrites the currently logged in userExample usage:
const { mockFirebase } = require('firestore-jest-mock');
// Create a fake Firestore with a `users` and `posts` collection
mockFirebase({
database: {
users: [
{ id: 'abc123', name: 'Homer Simpson' },
{ id: 'abc456', name: 'Lisa Simpson' },
],
posts: [{ id: '123abc', title: 'Really cool title' }],
},
});
This will populate a fake database with a users
and posts
collection.
Now you can write queries or requests for data just as you would with Firestore:
const { mockCollection } = require('firestore-jest-mock/mocks/firestore');
test('testing stuff', () => {
const firebase = require('firebase'); // or import firebase from 'firebase';
const db = firebase.firestore();
return db
.collection('users')
.get()
.then(userDocs => {
// Assert that a collection ID was referenced
expect(mockCollection).toHaveBeenCalledWith('users');
// Write other assertions here
});
});
A common case in Firestore is to store data in document subcollections. You can model these in firestore-jest-mock like so:
const { mockFirebase } = require('firestore-jest-mock');
// Using our fake Firestore from above:
mockFirebase({
database: {
users: [
{
id: 'abc123',
name: 'Homer Simpson',
},
{
id: 'abc456',
name: 'Lisa Simpson',
_collections: {
notes: [
{
id: 'note123',
text: 'This is a document in a subcollection!',
},
],
},
},
],
posts: [{ id: '123abc', title: 'Really cool title' }],
},
});
Similar to how the id
key models a document object, the _collections
key models a subcollection. You model each subcollection key in the same way that database
is modeled above: an object keyed by collection IDs and populated with document arrays.
This lets you model and validate more complex document access:
const { mockCollection, mockDoc } = require('firestore-jest-mock/mocks/firestore');
test('testing stuff', () => {
const firebase = require('firebase');
const db = firebase.firestore();
return db
.collection('users')
.doc('abc456')
.collection('notes')
.get()
.then(noteDocs => {
// Assert that a collection or document ID was referenced
expect(mockCollection).toHaveBeenNthCalledWith(1, 'users');
expect(mockDoc).toHaveBeenCalledWith('abc456');
expect(mockCollection).toHaveBeenNthCalledWith(2, 'notes');
// Write other assertions here
});
});
The job of the this library is not to test Firestore, but to allow you to test your code without hitting firebase. Take this example:
function maybeGetUsersInState(state) {
const query = firestore.collection('users');
if (state) {
query = query.where('state', '==', state);
}
return query.get();
}
We have a conditional query here. If you pass state
to this function, we will query against it; otherwise, we just get all of the users. So, you may want to write a test that ensures you are querying correctly:
const { mockFirebase } = require('firestore-jest-mock');
// Import the mock versions of the functions you expect to be called
const { mockCollection, mockWhere } = require('firestore-jest-mock/mocks/firestore');
describe('we can query', () => {
mockFirebase({
database: {
users: [
{
id: 'abc123',
name: 'Homer Simpson',
state: 'connecticut',
},
{
id: 'abc456',
name: 'Lisa Simpson',
state: 'alabama',
},
],
},
});
test('query with state', async () => {
await maybeGetUsersInState('alabama');
// Assert that we call the correct Firestore methods
expect(mockCollection).toHaveBeenCalledWith('users');
expect(mockWhere).toHaveBeenCalledWith('state', '==', 'alabama');
});
test('no state', async () => {
await maybeGetUsersInState();
// Assert that we call the correct Firestore methods
expect(mockCollection).toHaveBeenCalledWith('users');
expect(mockWhere).not.toHaveBeenCalled();
});
});
In this test, we don't necessarily care what gets returned from Firestore (it's not our job to test Firestore), but instead we try to assert that we built our query correctly.
If I pass a state to this function, does it properly query the
users
collection?
That's what we want to answer.
In jest, mocks will not reset between test instances unless you specify them to.
This can be an issue if you have two tests that make an asseration against something like mockCollection
.
If you call it in one test and assert that it was called in another test, you may get a false positive.
Luckily, jest offers a few methods to reset or clear your mocks.
beforeEach
to reset between each testjest.clearAllMocks();
mockCollection.mockClear();
The where
clause in the mocked Firestore will not actually filter the data at all.
We are not recreating Firestore in this mock, just exposing an API that allows us to write assertions.
It is also not the job of the developer (you) to test that Firestore filtered the data appropriately.
Your application doesn't double-check Firestore's response -- it trusts that it's always correct!
Method | Use | Method in Firestore |
---|---|---|
mockCollection | Assert the correct collection is being queried | collection |
mockCollectionGroup | Assert the correct collectionGroup is being queried | collectionGroup |
mockDoc | Assert the correct record is being fetched by id. Tells the mock you are fetching a single record | doc |
mockBatch | Assert batch was called | batch |
mockBatchDelete | Assert correct refs are passed | batch delete |
mockBatchCommit | Assert commit is called. Returns a promise | batch commit |
mockGetAll | Assert correct refs are passed. Returns a promise resolving to array of docs. | getAll |
mockUpdate | Assert correct params are passed to update. Returns a promise | update |
mockAdd | Assert correct params are passed to add. Returns a promise resolving to the doc with new id | add |
mockSet | Assert correct params are passed to set. Returns a promise | set |
mockDelete | Assert delete is called on ref. Returns a promise | delete |
Method | Use | Method in Firestore |
---|---|---|
mockGet | Assert get is called. Returns a promise resolving either to a single doc or querySnapshot | get |
mockWhere | Assert the correct query is written. Tells the mock you are fetching multiple records | where |
mockLimit | Assert limit is set properly | limit |
mockOrderBy | Assert correct field is passed to orderBy | orderBy |
mockOffset | Assert offset is set properly | offset |
mockStartAfter | Assert startAfter is called | startAfter |
mockStartAt | Assert startAt is called | startAt |
Method | Use | Method in Firestore |
---|---|---|
mockArrayRemoveFieldValue | Assert the correct elements are removed from an array | arrayRemove |
mockArrayUnionFieldValue | Assert the correct elements are added to an array | arrayUnion |
mockDeleteFieldValue | Assert the correct fields are removed from a document | delete |
mockIncrementFieldValue | Assert a number field is incremented by the correct amount | increment |
mockServerTimestampFieldValue | Assert a server Firebase.Timestamp value will be stored | serverTimestamp |
Method | Use | Method in Firestore |
---|---|---|
mockTimestampToDate | Assert the call and mock the result, or use the default implementation | toDate |
mockTimestampToMillis | Assert the call and mock the result, or use the default implementation | toMillis |
mockTimestampFromDate | Assert the call and mock the result, or use the default implementation | fromDate |
mockTimestampFromMillis | Assert the call and mock the result, or use the default implementation | fromMillis |
mockTimestampNow | Assert the call and mock the result, or use the default implementation | now |
Method | Use | Method in Firestore |
---|---|---|
mockGetTransaction | Assert transaction.get is called with correct params. Returns a promise | get |
mockGetAllTransaction | Assert transaction.getAll is called with correct params. Returns a promise | get |
mockSetTransaction | Assert transaction.set is called with correct params. Returns the transaction object | set |
mockUpdateTransaction | Assert transaction.update is called with correct params. Returns the transaction object | update |
mockDeleteTransaction | Assert transaction.delete is called with correct params. Returns the transaction object | delete |
Method | Use | Method in Firebase |
---|---|---|
mockCreateUserWithEmailAndPassword | Assert correct email and password are passed. Returns a promise | createUserWithEmailAndPassword |
mockGetUser | Assert correct user IDs are passed. Returns a promise | getUser |
mockDeleteUser | Assert correct ID is passed to delete method. Returns a promise | deleteUser |
mockSendVerificationEmail | Assert request for verification email was sent. Lives on the currentUser | sendVerificationEmail |
mockSetCustomUserClaims | Assert correct user ID and claims are set. | setCustomUserClaims |
mockSignInWithEmailAndPassword | Assert correct email and password were passed. Returns a promise | signInWithEmailAndPassword |
mockSendPasswordResetEmail | Assert correct email was passed. | sendPasswordResetEmail |
mockVerifyIdToken | Assert correct token is passed. Returns a promise | verifyIdToken |
We welcome all contributions to our projects! Filing bugs, feature requests, code changes, docs changes, or anything else you'd like to contribute are all more than welcome! More information about contributing can be found in the contributing guidelines.
To get set up, simply clone this repository and npm install
!
Upstatement strives to provide a welcoming, inclusive environment for all users. To hold ourselves accountable to that mission, we have a strictly-enforced code of conduct.
Upstatement is a digital transformation studio headquartered in Boston, MA that imagines and builds exceptional digital experiences. Make sure to check out our services, work, and open positions!
FAQs
Jest helper for mocking Google Cloud Firestore
We found that firestore-jest-mock demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.
Security News
Socket CEO Feross Aboukhadijeh discusses open source security challenges, including zero-day attacks and supply chain risks, on the Cyber Security Council podcast.
Security News
Research
Socket researchers uncover how threat actors weaponize Out-of-Band Application Security Testing (OAST) techniques across the npm, PyPI, and RubyGems ecosystems to exfiltrate sensitive data.