Created
June 8, 2021 23:48
-
-
Save johnkingzy/9097b5b65fc8a472ed51a35d7a0aba45 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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