Created
April 25, 2020 16:16
-
-
Save gotdibbs/63a298ab0752fa9a7185d00e8b76efff to your computer and use it in GitHub Desktop.
Mocking chainable APIs in Javascript, ex. mocking `useFirestore` from `react-redux-firebase`
This file contains hidden or 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
let firestoreDefinition = { | |
collection: { | |
doc: { | |
get: true, | |
set: true, | |
update: true, | |
destroy: true | |
} | |
}, | |
batch: { | |
commit: true, | |
delete: true, | |
update: true | |
} | |
}; | |
function buildMock(definition, root = null) { | |
if (!Object.keys(definition).length) { | |
return jest.fn(); | |
} | |
Object.keys(definition).map(k => { | |
const childMock = buildMock(definition[k], root || definition); | |
const mock = jest.fn(() => childMock); | |
// To avoid duplicating keys at the root, make each child mock available underneat the mock itself | |
Object.keys(childMock).forEach(childKey => { | |
mock[childKey] = childMock[childKey]; | |
}); | |
definition[k] = mock; | |
}); | |
return definition; | |
} | |
const mockFirestore = buildMock(firestoreDefinition); | |
export const useFirestore = () => { | |
return mockFirestore; | |
}; | |
useFirestore.mocks = mockFirestore; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment