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 🙏

© 2025 – Pkg Stats / Ryan Hefner

firestore-snapshot-utils

v2.2.1

Published

[![github license](https://img.shields.io/github/license/ericvera/firestore-snapshot-utils.svg?style=flat-square)](https://github.com/ericvera/firestore-snapshot-utils/blob/master/LICENSE) [![npm version](https://img.shields.io/npm/v/firestore-snapshot-ut

Readme

🔥 Firestore Snapshot Utils

github license npm version

A lightweight utility for testing Firestore database snapshots with precision.

Testing Firestore database changes shouldn't be painful. This lightweight utility makes it simple to track and verify Firestore collection changes in your tests.

✨ Features

  • 🔍 Snapshot Retrieval - Get snapshots from Firestore queries
  • 🔄 Change Detection - Track document additions, removals, and modifications
  • ⏱️ Timestamp Normalization - Compare timestamps reliably across test runs
  • 🔒 Property Masking - Ignore sensitive or variable properties in comparisons
  • 📊 Human-readable Diffs - See exactly what changed in your database
  • 🧪 Test Data Normalization - Normalize timestamps and buffers in any data structure for stable test snapshots
  • 📘 TypeScript Support - Fully typed API with strict type checking

📦 Installation

npm install firestore-snapshot-utils
# or
yarn add firestore-snapshot-utils

🚀 Quick Start

import {
  getDBSnapshot,
  getDBSnapshotChanges,
  getDiffFromDBSnapshotChanges,
  normalizeData,
} from 'firestore-snapshot-utils'

// Before operation
const beforeDocs = await getDBSnapshot(firestore.collection('users'))

// Run your database operations...

// After operation
const afterDocs = await getDBSnapshot(firestore.collection('users'))

// Compare snapshots
const changes = getDBSnapshotChanges(beforeDocs, afterDocs, {
  // Mask sensitive fields
  users: ['id', 'createdAt'],
})

// Generate readable diff
console.log(getDiffFromDBSnapshotChanges(changes))

📚 API Reference

getDBSnapshot

function getDBSnapshot(
  queries: Query | Query[],
): Promise<QueryDocumentSnapshot[]>

Gets documents from one or more Firestore queries as a flat array.

Example:

// Single collection
const docs = await getDBSnapshot(firestore.collection('users'))

// Multiple collections
const docs = await getDBSnapshot([
  firestore.collection('users'),
  firestore.collection('products'),
])

getDBSnapshotChanges

function getDBSnapshotChanges(
  beforeDocs: QueryDocumentSnapshot[],
  afterDocs: QueryDocumentSnapshot[],
  maskKeys: Record<string, string[]> = {},
  debugOptions: { logTimestamps?: boolean } = {},
): DBSnapshotChanges

Compares two document sets and identifies what changed.

Example:

const changes = getDBSnapshotChanges(beforeDocs, afterDocs, {
  users: ['id', 'createdAt'], // Mask these fields
  products: ['updatedAt'],
})

getDiffFromDBSnapshotChanges

function getDiffFromDBSnapshotChanges(changes: DBSnapshotChanges): string

Creates a human-readable diff from database changes.

Example with Jest:

expect(getDiffFromDBSnapshotChanges(changes)).toMatchInlineSnapshot()

normalizeData

function normalizeData<T = unknown>(
  data: T,
  options?: { logTimestamps?: boolean },
): T

Normalizes Firestore Timestamp and Buffer objects in any data structure for deterministic testing.

Example:

import { Timestamp } from 'firebase-admin/firestore'

const testData = {
  createdAt: new Timestamp(1234567890, 0),
  user: {
    lastLogin: new Timestamp(1234567891, 0),
  },
}

const normalized = normalizeData(testData)

// Use in tests for stable snapshots
expect(normalizeData(actualData)).toMatchInlineSnapshot(`
  Object {
    "createdAt": "/Timestamp 0000/",
    "user": Object {
      "lastLogin": "/Timestamp 0001/",
    },
  }
`)

🧪 Testing Example

describe('User profile update', () => {
  it('should update user data correctly', async () => {
    // Before state
    const beforeDocs = await getDBSnapshot(
      firestore.collection('users').where('id', '==', userId),
    )

    // Run operation
    await updateUserProfile(userId, { name: 'New Name' })

    // After state
    const afterDocs = await getDBSnapshot(
      firestore.collection('users').where('id', '==', userId),
    )

    // Compare with masked timestamps
    const changes = getDBSnapshotChanges(beforeDocs, afterDocs, {
      users: ['updatedAt'],
    })

    // Verify against snapshot
    expect(getDiffFromDBSnapshotChanges(changes)).toMatchInlineSnapshot(`
      "DB DIFF

      --------------------------------
       MODIFIED (path: users/[ID])
      --------------------------------
      - Expected
      + Received

        Object {
      -   "name": "Old Name",
      +   "name": "New Name",
        }"
    `)
  })
})

📝 Notes

  • Timestamps are automatically normalized for consistent comparisons
  • Buffer objects are converted to base64url strings for reliable diff generation
  • The normalizeData function can be used standalone to normalize test data with Timestamps and Buffers

🤝 AI Disclosure

This library's documentation has been enhanced with AI assistance. All code and functionality has been carefully designed and tested by humans.

📄 License

MIT