Skip to content

Instantly share code, notes, and snippets.

@johnkingzy
Created June 8, 2021 23:48
Show Gist options
  • Save johnkingzy/9097b5b65fc8a472ed51a35d7a0aba45 to your computer and use it in GitHub Desktop.
Save johnkingzy/9097b5b65fc8a472ed51a35d7a0aba45 to your computer and use it in GitHub Desktop.
const mockInitializeApp = jest.fn();
const mockCert = jest.fn();
const defaultOptions = {
includeIdsInData: false,
mutable: false,
};
class FakeAuth {
constructor() {
}
createUser() {
return Promise.resolve('OK')
}
}
const firebaseStub = (overrides, options = defaultOptions) => {
const { FakeFirestore } = require('firestore-jest-mock');
// Prepare namespaced classes
function firestoreConstructor() {
return new FakeFirestore(overrides.database, options);
}
firestoreConstructor.Query = FakeFirestore.Query;
firestoreConstructor.CollectionReference = FakeFirestore.CollectionReference;
firestoreConstructor.DocumentReference = FakeFirestore.DocumentReference;
firestoreConstructor.FieldValue = FakeFirestore.FieldValue;
firestoreConstructor.Timestamp = FakeFirestore.Timestamp;
firestoreConstructor.Transaction = FakeFirestore.Transaction;
firestoreConstructor.FieldPath = FakeFirestore.FieldPath;
// The Firebase mock
return {
initializeApp: mockInitializeApp,
credential: {
cert: mockCert,
},
auth() {
return new FakeAuth();
},
firestore: firestoreConstructor,
};
};
const mockFirebase = (overrides = {}, options = defaultOptions) => {
mockModuleIfFound('firebase', overrides, options);
mockModuleIfFound('firebase-admin', overrides, options);
};
function mockModuleIfFound(moduleName, overrides, options) {
try {
require.resolve(moduleName);
jest.doMock(moduleName, () => firebaseStub(overrides, options));
} catch (e) {
// eslint-disable-next-line no-console
console.info(`Module ${moduleName} not found, mocking skipped.`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment