firestore-node-mock 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,57 @@
1
+ import { mock } from 'node:test';
2
+
3
+ export const mockArrayUnionFieldValue = mock.fn();
4
+ export const mockArrayRemoveFieldValue = mock.fn();
5
+ export const mockDeleteFieldValue = mock.fn();
6
+ export const mockIncrementFieldValue = mock.fn();
7
+ export const mockServerTimestampFieldValue = mock.fn();
8
+
9
+ export class FieldValue {
10
+ constructor(type, value) {
11
+ this.type = type;
12
+ this.value = value;
13
+ }
14
+
15
+ isEqual(other) {
16
+ return other instanceof FieldValue && other.type === this.type && other.value === this.value;
17
+ }
18
+
19
+ static arrayUnion(elements = []) {
20
+ mockArrayUnionFieldValue(...arguments);
21
+ if (!Array.isArray(elements)) {
22
+ elements = [elements];
23
+ }
24
+ return new FieldValue('arrayUnion', elements);
25
+ }
26
+
27
+ static arrayRemove(elements) {
28
+ mockArrayRemoveFieldValue(...arguments);
29
+ if (!Array.isArray(elements)) {
30
+ elements = [elements];
31
+ }
32
+ return new FieldValue('arrayRemove', elements);
33
+ }
34
+
35
+ static increment(amount = 1) {
36
+ mockIncrementFieldValue(...arguments);
37
+ return new FieldValue('increment', amount);
38
+ }
39
+
40
+ static serverTimestamp() {
41
+ mockServerTimestampFieldValue(...arguments);
42
+ return new FieldValue('serverTimestamp');
43
+ }
44
+
45
+ static delete() {
46
+ mockDeleteFieldValue(...arguments);
47
+ return new FieldValue('delete');
48
+ }
49
+ }
50
+
51
+ export const mocks = {
52
+ mockArrayUnionFieldValue,
53
+ mockArrayRemoveFieldValue,
54
+ mockDeleteFieldValue,
55
+ mockIncrementFieldValue,
56
+ mockServerTimestampFieldValue,
57
+ };
@@ -0,0 +1,37 @@
1
+ import { Mock } from 'node:test';
2
+ import type { FirebaseUser, FakeAuth } from './auth.js';
3
+ import type { FakeFirestore } from './firestore.js';
4
+
5
+ export interface DatabaseDocument {
6
+ id: string;
7
+ _collections?: DatabaseCollections;
8
+ [key: string]: unknown;
9
+ }
10
+
11
+ export interface DatabaseCollections {
12
+ [collectionName: string]: Array<DatabaseDocument> | undefined;
13
+ }
14
+
15
+ export type FakeFirestoreDocumentData = Record<string, unknown>;
16
+
17
+ export interface StubOverrides {
18
+ database?: DatabaseCollections;
19
+ currentUser?: FirebaseUser;
20
+ }
21
+
22
+ type DefaultOptions = typeof import('./helpers/defaultMockOptions.js');
23
+ export interface StubOptions extends Partial<DefaultOptions> {}
24
+
25
+ export interface FirebaseMock {
26
+ initializeApp: Mock<any>;
27
+ credential: {
28
+ cert: Mock<any>;
29
+ };
30
+ auth(): FakeAuth;
31
+ firestore(): FakeFirestore;
32
+ }
33
+
34
+ export const firebaseStub: (overrides?: StubOverrides, options?: StubOptions) => FirebaseMock;
35
+ export const mockFirebase: (overrides?: StubOverrides, options?: StubOptions) => void;
36
+ export const mockInitializeApp: Mock<any>;
37
+ export const mockCert: Mock<any>;
@@ -0,0 +1,79 @@
1
+ import { mock } from 'node:test';
2
+ import { createRequire } from 'node:module';
3
+ import { FakeFirestore } from './firestore.js';
4
+ import { FakeAuth } from './auth.js';
5
+ import defaultOptions from './helpers/defaultMockOptions.js';
6
+
7
+ const require = createRequire(import.meta.url);
8
+
9
+ export const mockInitializeApp = mock.fn();
10
+ export const mockCert = mock.fn();
11
+
12
+ let activeOverrides = {};
13
+ let activeOptions = defaultOptions;
14
+ const mockedModules = new Set();
15
+
16
+ export const firebaseStub = () => {
17
+ // Prepare namespaced classes
18
+ function firestoreConstructor() {
19
+ return new FakeFirestore(activeOverrides.database, activeOptions);
20
+ }
21
+
22
+ firestoreConstructor.Query = FakeFirestore.Query;
23
+ firestoreConstructor.CollectionReference = FakeFirestore.CollectionReference;
24
+ firestoreConstructor.DocumentReference = FakeFirestore.DocumentReference;
25
+ firestoreConstructor.FieldValue = FakeFirestore.FieldValue;
26
+ firestoreConstructor.Timestamp = FakeFirestore.Timestamp;
27
+ firestoreConstructor.Transaction = FakeFirestore.Transaction;
28
+ firestoreConstructor.FieldPath = FakeFirestore.FieldPath;
29
+
30
+ //Remove methods which do not exist in Firebase
31
+ delete firestoreConstructor.DocumentReference.prototype.listCollections;
32
+
33
+ // The Firebase mock
34
+ return {
35
+ initializeApp: mockInitializeApp,
36
+
37
+ credential: {
38
+ cert: mockCert,
39
+ },
40
+
41
+ auth() {
42
+ return new FakeAuth(activeOverrides.currentUser);
43
+ },
44
+
45
+ firestore: firestoreConstructor,
46
+ };
47
+ };
48
+
49
+ export const mockFirebase = (overrides = {}, options = defaultOptions) => {
50
+ activeOverrides = overrides;
51
+ activeOptions = options;
52
+
53
+ const moduleFound =
54
+ mockModuleIfFound('firebase') |
55
+ mockModuleIfFound('firebase-admin');
56
+
57
+ if (!moduleFound && mockedModules.size === 0) {
58
+ console.info(`Neither 'firebase' nor 'firebase-admin' modules found, mocking skipped.`);
59
+ }
60
+ };
61
+
62
+ function mockModuleIfFound(moduleName) {
63
+ if (mockedModules.has(moduleName)) {
64
+ return true;
65
+ }
66
+ try {
67
+ require.resolve(moduleName);
68
+ const stub = firebaseStub();
69
+ mock.module(moduleName, {
70
+ defaultExport: stub,
71
+ namedExports: stub,
72
+ });
73
+ mockedModules.add(moduleName);
74
+ return true;
75
+ } catch (e) {
76
+ // console.error(`Error mocking ${moduleName}:`, e);
77
+ return false;
78
+ }
79
+ }
@@ -0,0 +1,181 @@
1
+ import { Mock } from 'node:test';
2
+ import type { FieldValue } from './fieldValue.js';
3
+ import type { Query } from './query.js';
4
+ import type { Timestamp } from './timestamp.js';
5
+ import type { Transaction } from './transaction.js';
6
+ import type { FieldPath } from './path.js';
7
+
8
+ import type { MockedDocument, DocumentData } from './helpers/buildDocFromHash.js';
9
+ import type { MockedQuerySnapshot } from './helpers/buildQuerySnapShot.js';
10
+
11
+ interface DatabaseDocument extends DocumentData {
12
+ id: string;
13
+ _collections?: DatabaseCollections;
14
+ }
15
+
16
+ interface DatabaseCollections {
17
+ [collectionName: string]: Array<DatabaseDocument> | undefined;
18
+ }
19
+
20
+ interface SetOptions {
21
+ merge?: boolean;
22
+ }
23
+
24
+ interface FirestoreBatch {
25
+ delete(): FirestoreBatch;
26
+ set(doc: DocumentReference, data: DocumentData, options?: SetOptions): FirestoreBatch;
27
+ update(doc: DocumentReference, data: DocumentData): FirestoreBatch;
28
+ create(doc: DocumentReference, data: DocumentData): FirestoreBatch;
29
+ commit(): Promise<void>;
30
+ }
31
+
32
+ export type FakeFirestoreDatabase = DatabaseCollections;
33
+
34
+ export class FakeFirestore {
35
+ static FieldValue: typeof FieldValue;
36
+ static Timestamp: typeof Timestamp
37
+ static Query: typeof Query;
38
+ static Transaction: typeof Transaction;
39
+ static FieldPath: typeof FieldPath;
40
+
41
+ static DocumentReference: typeof DocumentReference;
42
+ static CollectionReference: typeof CollectionReference;
43
+
44
+ database: FakeFirestoreDatabase;
45
+ options: Record<string, never>;
46
+ query: Query;
47
+ collectionName: string;
48
+
49
+ constructor(stubbedDatabase?: DatabaseCollections, options?: Record<string, never>);
50
+
51
+ getAll(): Array<MockedQuerySnapshot>;
52
+ batch(): FirestoreBatch;
53
+ settings(): void;
54
+ useEmulator(): void;
55
+ collection(collectionName: string): CollectionReference;
56
+ collectionGroup(collectionName: string): Query;
57
+ doc(path: string): DocumentReference;
58
+ runTransaction<T>(updateFunction: (transaction: Transaction) => Promise<T>): Promise<T>;
59
+ recursiveDelete(ref: DocumentReference|CollectionReference): Promise<void>;
60
+ }
61
+
62
+ declare class DocumentReference {
63
+ id: string;
64
+ parent: CollectionReference;
65
+ firestore: FakeFirestore;
66
+ path: string;
67
+
68
+ constructor(id: string, parent: CollectionReference);
69
+
70
+ collection(collectionName: string): CollectionReference;
71
+ delete(): Promise<void>;
72
+ get(): Promise<MockedDocument>;
73
+
74
+ create(object: DocumentData): Promise<MockedDocument>;
75
+ update(object: DocumentData): Promise<MockedDocument>;
76
+ set(object: DocumentData): Promise<MockedDocument>;
77
+
78
+ isEqual(other: DocumentReference): boolean;
79
+
80
+ withConverter(): DocumentReference;
81
+
82
+ onSnapshot(callback: () => void, errorCallback: () => void): () => void;
83
+ onSnapshot(options: Record<string, never>, callback: () => void, errorCallback: () => void): () => void;
84
+
85
+ /** @deprecated Call the analagous method on a `Query` instance instead. */
86
+ orderBy(): never;
87
+
88
+ /** @deprecated Call the analagous method on a `Query` instance instead. */
89
+ limit(): never;
90
+
91
+ /** @deprecated Call the analagous method on a `Query` instance instead. */
92
+ offset(): never;
93
+
94
+ /** @deprecated Call the analagous method on a `Query` instance instead. */
95
+ startAfter(): never;
96
+
97
+ /** @deprecated Call the analagous method on a `Query` instance instead. */
98
+ startAt(): never;
99
+ }
100
+
101
+ declare class CollectionReference extends FakeFirestore.Query {
102
+ id: string;
103
+ parent: DocumentReference;
104
+ path: string;
105
+
106
+ constructor(id: string, parent: DocumentReference, firestore?: FakeFirestore);
107
+
108
+ doc(id?: string): DocumentReference;
109
+ get(): Promise<MockedQuerySnapshot>;
110
+ add(data: DocumentData): Promise<DocumentReference>;
111
+ isEqual(other: CollectionReference): boolean;
112
+
113
+ /**
114
+ * An internal method, meant mainly to be used by `get` and other internal objects to retrieve
115
+ * the list of database records referenced by this CollectionReference.
116
+ * @returns An array of mocked document records.
117
+ */
118
+ private _records(): Array<MockedDocument>
119
+ }
120
+
121
+ // Mocks exported from this module
122
+ export const mockBatch: Mock<any>;
123
+ export const mockRunTransaction: Mock<any>;
124
+ export const mockRecursiveDelete: Mock<any>;
125
+
126
+ export const mockCollection: Mock<any>;
127
+ export const mockCollectionGroup: Mock<any>;
128
+ export const mockDoc: Mock<any>;
129
+ export const mockCreate: Mock<any>;
130
+ export const mockUpdate: Mock<any>;
131
+ export const mockSet: Mock<any>;
132
+ export const mockAdd: Mock<any>;
133
+ export const mockDelete: Mock<any>;
134
+ export const mockSettings: Mock<any>;
135
+
136
+ // FIXME: We should decide whether this should be exported from auth or firestore
137
+ export const mockUseEmulator: Mock<any>;
138
+ export const mockListDocuments: Mock<any>;
139
+
140
+ export const mockBatchDelete: Mock<any>;
141
+ export const mockBatchCommit: Mock<any>;
142
+ export const mockBatchUpdate: Mock<any>;
143
+ export const mockBatchSet: Mock<any>;
144
+ export const mockBatchCreate: Mock<any>;
145
+
146
+ export const mockOnSnapShot: Mock<any>;
147
+
148
+ // Mocks exported from FieldValue
149
+ export const mockArrayUnionFieldValue: Mock<any>;
150
+ export const mockArrayRemoveFieldValue: Mock<any>;
151
+ export const mockDeleteFieldValue: Mock<any>;
152
+ export const mockIncrementFieldValue: Mock<any>;
153
+ export const mockServerTimestampFieldValue: Mock<any>;
154
+
155
+ // Mocks exported from Query
156
+ export const mockGet: Mock<any>;
157
+ export const mockWhere: Mock<any>;
158
+ export const mockLimit: Mock<any>;
159
+ export const mockOrderBy: Mock<any>;
160
+ export const mockOffset: Mock<any>;
161
+ export const mockStartAfter: Mock<any>;
162
+ export const mockStartAt: Mock<any>;
163
+ export const mockQueryOnSnapshot: Mock<any>;
164
+ export const mockQueryOnSnapshotUnsubscribe: Mock<any>;
165
+ export const mockWithConverter: Mock<any>;
166
+
167
+ // Mocks exported from Timestamp
168
+ export const mockTimestampToDate: Mock<any>;
169
+ export const mockTimestampToMillis: Mock<any>;
170
+ export const mockTimestampFromDate: Mock<any>;
171
+ export const mockTimestampFromMillis: Mock<any>;
172
+ export const mockTimestampNow: Mock<any>;
173
+
174
+ // Mocks exported from Transaction
175
+ export const mockGetAll: Mock<any>;
176
+ export const mockGetAllTransaction: Mock<any>;
177
+ export const mockGetTransaction: Mock<any>;
178
+ export const mockSetTransaction: Mock<any>;
179
+ export const mockUpdateTransaction: Mock<any>;
180
+ export const mockDeleteTransaction: Mock<any>;
181
+ export const mockCreateTransaction: Mock<any>;