Gathering detailed insights and metrics for ts-firebase-mock
Gathering detailed insights and metrics for ts-firebase-mock
Gathering detailed insights and metrics for ts-firebase-mock
Gathering detailed insights and metrics for ts-firebase-mock
ts-mock-firebase
Mock objects for Firebase
mock-firebase-ts
Mock objects for Firebase
ts-mock-firebase-updated
Mock objects for Firebase
@j2blasco/ts-auth
TypeScript authentication abstraction library that eliminates vendor lock-in and provides mock-free testing for both frontend and backend authentication systems
npm install ts-firebase-mock
Typescript
Module System
Node Version
NPM Version
TypeScript (100%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
1 Stars
52 Commits
1 Watchers
1 Branches
1 Contributors
Updated on May 02, 2025
Latest Version
0.0.25
Package Id
ts-firebase-mock@0.0.25
Unpacked Size
281.19 kB
Size
41.08 kB
File Count
51
NPM Version
10.8.3
Node Version
22.9.0
Published on
May 02, 2025
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
ts-firebase-mock
is a TypeScript library designed to simulate Firestore (a NoSQL cloud database from Firebase) for testing purposes. This package mimics Firestore's core functionality, allowing developers to write unit tests without requiring a real Firestore instance. It operates entirely in-memory, providing a lightweight solution for testing Firestore interactions locally.
You can install ts-firebase-mock
via npm or yarn.
1npm install ts-firebase-mock 2or 3yarn add ts-firebase-mock
To create a mock Firestore instance, simply instantiate the FirestoreMock class. This will simulate Firestore's collection and document behavior.
1import MockedFirebase from 'ts-firebase-mock'; 2 3// Create associate mocked 4const firebase = new MockedFirebase(); 5 6const firestore = firebase.firestore(); 7const fireauth = firebase.auth();
The MockedFireAuth class provides a simulated Firebase Authentication API for testing purposes.
This method checks if a given token (simulated as a user's uid) is valid and returns corresponding user details.
1import MockedFireAuth from './MockedFireAuth'; 2 3const auth = new MockedFireAuth(); 4try { 5 const decodedToken = await auth.verifyIdToken('mock-user-uid'); 6 console.log('Decoded Token:', decodedToken); 7} catch (error) { 8 console.error('Error verifying token:', error.message); 9}
This method generates a new user with a unique uid and stores their email and password in the mock database.
1import MockedFireAuth from './MockedFireAuth'; 2 3const auth = new MockedFireAuth(); 4try { 5 const newUser = await auth.createUser('newuser@example.com', 'securePassword123'); 6 console.log('User Created:', newUser); 7} catch (error) { 8 console.error('Error creating user:', error.message); 9}
This method checks if the provided email and password match an existing user in the mock database and returns the user data if valid.
1import MockedFireAuth from './MockedFireAuth'; 2 3const auth = new MockedFireAuth(); 4try { 5 const user = await auth.signInWithEmailAndPassword('test@example.com', 'password123'); 6 console.log('User Signed In:', user); 7} catch (error) { 8 console.error('Error signing in:', error.message); 9}
This method simulates a sign-in process using a provider like Google, returning a pre-defined user with verified email.
1import MockedFireAuth from './MockedFireAuth'; 2 3const auth = new MockedFireAuth(); 4try { 5 const googleUser = await auth.signInWithProvider('google'); 6 console.log('User Signed In via Google:', googleUser); 7} catch (error) { 8 console.error('Error signing in with provider:', error.message); 9}
You can add documents to collections and subcollections using the add method. Each document will have a unique ID generated by default.
1// Collections 2const usersCollection = firestore.collection('users'); 3usersCollection.add({ name: 'Alice', age: 30 }); 4usersCollection.add({ name: 'Bob', age: 25 }); 5 6// Subcollections 7const usersCollection = firestore.collection('users'); 8const userDocRef = usersCollection.doc('user1'); 9// Adding a document to a subcollection under the 'user1' document 10const addressesCollection = userDocRef.collection('addresses'); 11addressesCollection.add({ city: 'Paris', zip: '75000' }); 12 13// Also subcollections 14const reviewsCollection = addressesCollection.doc('address1').collection('reviews'); 15reviewsCollection.add({ review: 'Great place!', rating: 5 });
To retrieve documents, you can call get() on a collection. This will return all documents in the collection.
1const users = usersCollection.get(); 2console.log(users); // Output: [MockedDocumentSnapshot, MockedDocumentSnapshot]
You can filter documents using the where method, which allows you to specify field values, operators, and the value to filter by. It supports operators like ==, >, <, >=, <=, !=, in, and not-in.
1const filteredUsers = usersCollection.where('age', '>', 30).get(); 2console.log(filteredUsers.length); // Output: 1 (users with age > 30) 3 4// Example: Users not aged 30 5const not30YearsOld = usersCollection.where('age', '!=', 30).get(); 6console.log(not30YearsOld.size); // Output: 2 7 8// Example: Users aged 25 or 35 9const agesIn = usersCollection.where('age', 'in', [25, 35]).get(); 10console.log(agesIn.size); // Output: 2 11 12// Example: Users not aged 30 or 35 13const agesNotIn = usersCollection.where('age', 'not-in', [30, 35]).get(); 14console.log(agesNotIn.size); // Output: 1 15
To sort the results of a query, use the orderBy method, which allows sorting by a specified field in ascending or descending order.
1const orderedUsers = usersCollection.orderBy('age', 'desc').get(); 2console.log(orderedUsers[0].data().age); // Output: 30 (highest age)
You can limit the number of documents returned by a query using the limit method.
1const limitedUsers = usersCollection.limit(1).get(); 2console.log(limitedUsers.length); // Output: 1
Each document in a collection has a reference via the doc() method, and you can retrieve a snapshot of the document with the get() method.
1const userDocRef = usersCollection.doc('user-id'); 2const userDoc = userDocRef.get(); 3console.log(userDoc.data()); // Output: { name: 'Alice', age: 30 }
The arrayUnion and arrayRemove methods are used to modify array fields within a document.
1// Add a new user with interests 2const userDocRef = usersCollection.doc('user-id'); 3userDocRef.set({ name: 'Daisy', interests: ['reading', 'swimming'] }); 4 5// Use arrayUnion to add a new interest without duplicating existing values 6userDocRef.arrayUnion('interests', 'coding'); 7console.log(userDocRef.get().data().interests); // Output: ['reading', 'swimming', 'coding'] 8 9// Use arrayUnion again to attempt adding an existing interest 10userDocRef.arrayUnion('interests', 'swimming'); 11console.log(userDocRef.get().data().interests); // Output remains: ['reading', 'swimming', 'coding'] 12 13// Use arrayRemove to remove an interest 14userDocRef.arrayRemove('interests', 'reading'); 15console.log(userDocRef.get().data().interests); // Output: ['swimming', 'coding'] 16
You can listen for real-time updates on a document using the onSnapshot method. This method accepts a callback function that gets called whenever the document is updated.
1const userDocRef = usersCollection.doc('user-id'); 2userDocRef.onSnapshot((docSnapshot) => { 3 console.log(docSnapshot.data()); // Output: updated data of the document 4});
You can update a document using the set method on a document reference. The set method allows for data replacement or merging depending on the provided options.
1// Update document data 2userDocRef.update({ age: 41 }); 3 4// Replace document data 5userDocRef.set({ name: 'Charlie', age: 40 }); 6 7// Merge document data 8userDocRef.set({ age: 41 }, { merge: true }); 9
FirestoreMock The main class that simulates Firestore functionality.
Simulates a Firestore collection of documents.
add(data: Record<string, any>): MockedDocumentReference
- Adds a document to the collection.get(): MockedDocumentSnapshot[]
- Retrieves all documents in the collection.where(field: string, operator: string, value: any): this
- Filters documents by field values.orderBy(field: string, direction: 'asc' | 'desc' = 'asc'): this
- Orders documents by field value.limit(count: number): this
- Limits the number of documents returned by the query.doc(id: string): MockedDocumentReference
- Retrieves a document reference by ID.Represents a reference to a document.
set(data: Record<string, any>, options?: { merge: boolean }): void
- Sets data for the document, with an option to merge.get(): MockedDocumentSnapshot
- Retrieves a snapshot of the document.arrayUnion(field: string, value: any): void
- Adds a value to an array field in the document, avoiding duplicates.arrayRemove(field: string, value: any): void
- Removes a value from an array field in the document, if it exists.delete(): void
- Deletes the document.onSnapshot(callback: Function): void
- Adds a listener for document changes.exists(): boolean
- Return if document existRepresents a snapshot of a document retrieved from a collection.
data(): Record<string, any>
- Retrieves the document data.exists(): boolean
- Return if document is existget(field: string): any
- Return specific field in documentRepresents a mocked firestore.
collection(collectionPath: string): MockedCollection
- Retreive or create collection with nameflush(): void
- Flush all datas in mocked firestoreHere’s a complete example showing how you can use ts-firebase-mock to add, retrieve, and update documents:
1import { MockedFirebase } from 'ts-firebase-mock'; 2 3// Create associate mocked 4const firebase = new MockedFirebase(); 5 6const firestore = firebase.firestore(); 7const fireauth = firebase.auth(); 8 9// Create a collection 10const usersCollection = firestore.collection('users'); 11 12// Add some users 13usersCollection.add({ name: 'Alice', age: 30 }); 14usersCollection.add({ name: 'Bob', age: 25 }); 15usersCollection.add({ name: 'Charlie', age: 35 }); 16 17// Retrieve all users 18const users = usersCollection.get(); 19console.log(users); // Output: [MockedDocumentSnapshot, MockedDocumentSnapshot, MockedDocumentSnapshot] 20 21// Filter users above age 30 22const usersAbove30 = usersCollection.where('age', '>', 30).get(); 23console.log(usersAbove30.length); // Output: 1 (Only Charlie) 24 25// Order users by age in descending order 26const orderedUsers = usersCollection.orderBy('age', 'desc').get(); 27console.log(orderedUsers[0].data()); // Output: { name: 'Charlie', age: 35 } 28 29// Limit the results to 2 users 30const limitedUsers = usersCollection.limit(2).get(); 31console.log(limitedUsers.length); // Output: 2 32 33// Update a user 34const userDocRef = usersCollection.doc('user-id'); 35userDocRef.set({ age: 31 }, { merge: true }); 36 37// Delete a user 38const deleteUserDocRef = usersCollection.doc('user-to-remove').delete();
This project is licensed under the MIT License - see the LICENSE file for details.
No vulnerabilities found.
No security vulnerabilities found.