Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@gotdibbs
Created April 25, 2020 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gotdibbs/63a298ab0752fa9a7185d00e8b76efff to your computer and use it in GitHub Desktop.
Save gotdibbs/63a298ab0752fa9a7185d00e8b76efff to your computer and use it in GitHub Desktop.
Mocking chainable APIs in Javascript, ex. mocking `useFirestore` from `react-redux-firebase`
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