Created
June 26, 2019 23:36
-
-
Save doramatadora/57926bde10b525545d20f9d6ad19f359 to your computer and use it in GitHub Desktop.
Mocking chained APIs with Jest, the easy way
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
// 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