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

ts-firebase-simulator

v0.12.2

Published

TypeScript-first in-memory Firebase stubs for unit testing

Downloads

43

Readme

Firebase Simulator

An in-memory, TypeScript simulator for some firebase services - for use in unit tests.

Examples

The easiest way to understand it to look at the examples directory for targeted, single-concept code samples covering:

  • Firestore CRUD, queries, transactions, triggers
  • Cloud Storage operations
  • Cloud Tasks creation and assertions
  • Dependency injection patterns

The Problem

Firebase doesn't provide TypeScript interfaces for its classes, making it difficult to write unit tests that swap real implementations for test doubles. This package aims to solve that problem.

// You can't do this - Firestore is a concrete class, not an interface
class MyService {
    constructor(private db: Firestore) {} // No nice way to inject a stub or mock
}

Firebase's SDK exports concrete classes (Firestore, CloudTasksClient, Storage) without corresponding interfaces. This means:

  • You can't create mock implementations for unit testing
  • You're forced to use the Firebase Emulator for all tests (slow)
  • Dependency injection patterns don't work

The Solution

This package provides:

  1. Interfaces (IFirestoreDatabase, ICloudTasksClient, IStorage) that mirror Firebase's API
  2. Stub implementations (StubFirestoreDatabase, StubCloudTasksClient, StubStorage) for fast, in-memory unit tests
  3. Wrapper factories (createFirestoreDatabase, createCloudTasksClient, createStorage) that adapt real Firebase instances to the interfaces
import { IFirestoreDatabase, StubFirestoreDatabase, createFirestoreDatabase } from 'ts-firebase-simulator';

class MyService {
    constructor(private db: IFirestoreDatabase) {} // Now accepts both real and stub
}

// In production
const realDb = createFirestoreDatabase(getFirestore());
const service = new MyService(realDb);

// In unit tests
const stubDb = new StubFirestoreDatabase();
const service = new MyService(stubDb);

Installation

npm install ts-firebase-simulator

Quick Start

import {
    IFirestoreDatabase,
    StubFirestoreDatabase,
    createFirestoreDatabase,
    Timestamp,
} from 'ts-firebase-simulator';

// In unit tests - fast, in-memory, no Firebase connection
const db = new StubFirestoreDatabase();

await db.collection('users').doc('user-1').set({
    name: 'Alice',
    createdAt: Timestamp.now(),
});

const snapshot = await db.collection('users').doc('user-1').get();
console.log(snapshot.data()); // { name: 'Alice', createdAt: ... }

// Clean up between tests
db.clear();

Interfaces

IFirestoreDatabase

Use instead of Firestore from firebase-admin/firestore:

interface IFirestoreDatabase {
    collection(path: string): ICollectionReference;
    doc(path: string): IDocumentReference;
    collectionGroup(collectionId: string): IQuery;
    batch(): IWriteBatch;
    runTransaction<T>(fn: (transaction: ITransaction) => Promise<T>): Promise<T>;
}

ICloudTasksClient

Use instead of CloudTasksClient from @google-cloud/tasks:

interface ICloudTasksClient {
    queuePath(project: string, location: string, queue: string): string;
    createTask(request: CreateTaskRequest): Promise<[Task]>;
}

IStorage

Use instead of Storage from firebase-admin/storage:

interface IStorage {
    bucket(name?: string): IStorageBucket;
}

interface IStorageBucket {
    readonly name: string;
    file(path: string): IStorageFile;
    getFiles(options?: { prefix?: string }): Promise<[IStorageFile[]]>;
}

interface IStorageFile {
    readonly name: string;
    save(data: StorageFileContent, options?: StorageSaveOptions): Promise<void>;
    makePublic(): Promise<void>;
    delete(): Promise<void>;
    exists(): Promise<[boolean]>;
    getMetadata(): Promise<[StorageFileMetadata]>;
    createReadStream(): Readable;
    getSignedUrl(config: GetSignedUrlConfig): Promise<[string]>;
}

Stub Features

StubFirestoreDatabase

Full in-memory Firestore implementation:

  • Document CRUD (set, get, update, delete)
  • Collections and subcollections
  • Queries (where, orderBy, limit, offset, startAfter)
  • Collection group queries
  • Transactions and batch writes
  • Real-time listeners (onSnapshot)
  • Firestore triggers for testing Cloud Functions

StubCloudTasksClient

In-memory Cloud Tasks:

  • Task creation with HTTP request details
  • Queue path generation
  • Task tracking for assertions (getEnqueuedTasks(), getLastEnqueuedTask())

StubStorage

In-memory Firebase Storage:

  • File save/delete operations
  • Metadata support (getMetadata())
  • File existence checks (exists())
  • Read streams (createReadStream())
  • Signed URL generation (getSignedUrl()) - generates mock URLs without requiring credentials
  • File listing (getFiles(), getAllFiles(), getFile())
  • Test utilities (seedFile(), clear())

Production Wrappers

Wrap real Firebase instances to use the interfaces:

import { getFirestore } from 'firebase-admin/firestore';
import { getStorage } from 'firebase-admin/storage';
import { CloudTasksClient } from '@google-cloud/tasks';
import { createFirestoreDatabase, createCloudTasksClient, createStorage } from 'ts-firebase-simulator';

// Firestore
const db: IFirestoreDatabase = createFirestoreDatabase(getFirestore());

// Cloud Tasks
const tasks: ICloudTasksClient = createCloudTasksClient(); // Uses real CloudTasksClient internally

// Storage
const storage: IStorage = createStorage(getStorage());

Testing Firestore Triggers

Register triggers to test Cloud Functions behavior:

const db = new StubFirestoreDatabase();

const unregister = db.registerTrigger('users/{userId}', {
    onCreate: (change) => console.log('Created:', change.after.data()),
    onUpdate: (change) => console.log('Updated:', change.before.data(), '->', change.after.data()),
    onDelete: (change) => console.log('Deleted:', change.before.data()),
});

await db.collection('users').doc('user-1').set({ name: 'Alice' });
// Logs: Created: { name: 'Alice' }

unregister();

Contributing

This package includes integration tests that verify stub behavior matches real Firebase. See CONTRIBUTING.md for setup instructions.

License

MIT