npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

firestore-test-utils

v0.1.0

Published

Firestore Jest testing utilities for mocking Firebase Firestore in unit tests.

Readme

In-Memory Firestore Mock for Jest

NPM Version License: MIT

A lightweight, zero-dependency, in-memory mock of the Firebase Admin Firestore SDK for Jest. Designed to make testing your Firestore-dependent backend logic fast, reliable, and easy, without needing a live database connection or the Firebase emulators.

The Problem It Solves

Testing code that interacts with Firestore can be challenging. You either have to connect to a real database (which is slow, costly, and brittle) or use the official Firebase emulators (which can be complex to set up and manage in a CI environment).

This mock utility solves this by providing an in-memory simulation of Firestore that behaves like the real thing for common operations, including:

  • Correctly handling Timestamp objects: Unlike simple JSON.stringify mocks, this utility preserves the .toDate() method on mock Timestamp objects, preventing common TypeError exceptions in tests.
  • Supporting complex queries: It handles chained where(), orderBy(), and limit() calls.
  • Subcollections: Natively supports operations on nested subcollections.
  • Batch writes: Provides a functional mock for batch() operations (set, update, delete).

Features

This mock supports a wide range of common Firestore operations:

Top-Level Methods

  • collection(path)
  • doc(path)
  • batch()

Querying

  • Chainable queries: collection().where().orderBy().limit().get()
  • get() on collections and documents.
  • where(field, op, value) with the following operators:
    • == (Equal to)
    • != (Not equal to)
    • < (Less than)
    • <= (Less than or equal to)
    • > (Greater than)
    • >= (Greater than or equal to)
    • in (In an array of values)
    • not-in (Not in an array of values)
    • array-contains
    • array-contains-any
  • orderBy(field, direction) with 'asc' or 'desc' direction.
  • limit(number) to restrict the number of returned documents.
  • Querying by document ID using the __name__ field path.

Document Manipulation

  • add(data) to add a new document with an auto-generated ID.
  • set(data, { merge: true }) to create or merge data into a document.
  • update(data) to modify an existing document.
  • delete() to remove a document.

Subcollections

  • Full support for doc('id').collection('subcollection').get() and all other query and document methods on subcollections.

Batch Operations

  • A functional mock for adminDb.batch() that supports:
    • batch.set(docRef, data)
    • batch.update(docRef, data)
    • batch.delete(docRef)
    • batch.commit()

Data Types

  • Timestamp Preservation: Correctly mocks Firestore Timestamp objects, preserving the .toDate() method to avoid type errors in tests.

Installation

npm install --save-dev in-memory-firestore-mock

Quick Start Guide

Here's how to get started with testing your Firestore-dependent server actions.

1. Mock the firebase-admin module

In your test file (e.g., my-service.test.ts), you need to tell Jest to use our mock instead of the real firebase-admin SDK.

// src/services/my-service.test.ts

// Import the utility from your test helpers
import { createFirestoreMock } from '@/lib/firestore-test-utils'; // Adjust path as needed

// Mock the firebaseAdmin module
let mockAdminDb;
jest.mock('@/lib/firebaseAdmin', () => ({
  get adminDb() {
    return mockAdminDb;
  },
}));

// Your function to test (example)
async function getAdminUsers() {
  const snapshot = await mockAdminDb.collection('users').where('role', '==', 'admin').get();
  return snapshot.docs.map(doc => doc.data());
}

// Your test suite
describe('My Firestore Service', () => {

  beforeEach(() => {
    // Reset the mock with new data for each test to ensure isolation
    const initialDbState = {
      users: {
        'user1': { name: 'Alice', role: 'admin' },
        'user2': { name: 'Bob', role: 'user' },
        'user3': { name: 'Charlie', role: 'admin' },
      }
    };
    mockAdminDb = createFirestoreMock(initialDbState);
  });

  it('should only return users with the admin role', async () => {
    // Act
    const adminUsers = await getAdminUsers();

    // Assert
    expect(adminUsers).toHaveLength(2);
    expect(adminUsers.map(u => u.name)).toEqual(expect.arrayContaining(['Alice', 'Charlie']));
  });
});

2. Using with Subcollections and Timestamps

The mock handles nested data and Timestamp objects gracefully.

// In your test file...
import { Timestamp } from 'firebase-admin/firestore'; // Import from the real library for type safety

describe('Subcollection and Timestamp Test', () => {

  beforeEach(() => {
    const now = new Date();
    const initialData = {
        'users/user1/posts': {
            'post1': { title: 'My First Post', createdAt: Timestamp.fromDate(now) }
        }
    };
    mockAdminDb = createFirestoreMock(initialData);
  });

  it('should retrieve a post from a subcollection', async () => {
    const postRef = mockAdminDb.collection('users').doc('user1').collection('posts').doc('post1');
    const postSnap = await postRef.get();

    expect(postSnap.exists).toBe(true);
    expect(postSnap.data().title).toBe('My First Post');
    // The .toDate() method will exist and work correctly!
    expect(postSnap.data().createdAt.toDate()).toBeInstanceOf(Date);
  });
});

API

createFirestoreMock(initialData?)

  • initialData (optional): An object representing the starting state of your database for a test.
    • Keys are collection paths. For subcollections, use the format 'collection/docId/subcollection'.
    • Values are objects where keys are document IDs and values are the document data.

Returns a mock Firestore instance with the methods listed in the "Features" section.

Contributing

Contributions are welcome! If you find a bug or have a feature request, please open an issue on our GitHub repository. If you'd like to contribute code, please open a pull request.

License

This project is licensed under the MIT License.