Skip to content

Instantly share code, notes, and snippets.

@doramatadora
Created June 26, 2019 23:36
Show Gist options
  • Save doramatadora/57926bde10b525545d20f9d6ad19f359 to your computer and use it in GitHub Desktop.
Save doramatadora/57926bde10b525545d20f9d6ad19f359 to your computer and use it in GitHub Desktop.
Mocking chained APIs with Jest, the easy way
// for when you want to mock/stub chained APIs
// useful with stuff like octokit, aws-sdk, neo4j-driver
// for avoiding nastiness, like, for e.g. octokit.git.getTree
// const octoStub = { octokit: { git: { getTree: jest.fn()) } } }
// this mocks/stubs everything to a specified depth
function mockChainedAPI(mock: any = jest.fn(), depth: number) {
return new Proxy({} as any, {
get: function(obj, prop) {
obj._depthCount = (obj._depthCount || 0) + 1;
if (obj._depthCount === depth) {
return mock;
}
obj[prop] = function() {
return this;
};
return obj[prop];
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment