Created
December 12, 2017 02:17
-
-
Save theKashey/e42f283158455b640cddd12441074507 to your computer and use it in GitHub Desktop.
"Proxyquire" inside the Jest
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
// anywhere | |
import proxyquire from '....../proxyquire.js' | |
// proxyquire.js | |
// use rewiremock to mock proxyquire | |
import rewiremock, { addPlugin, plugins, overrideEntryPoint } from 'rewiremock'; | |
import stackTrace from 'stack-trace'; | |
rewiremock.requireActual('babel-register'); | |
if (typeof jest !== 'undefined') { | |
// BYPASS JEST SANDBOX | |
// get the original test file location | |
const originalCaller = stackTrace | |
.get() | |
.map(stack => stack.getFileName()) | |
.filter(a => !!a) // some files has no name | |
.filter(a => a.indexOf('/') === 0) // some are virtial (ok, this will not in Win32) | |
.filter(a => a.indexOf(module.filename) < 0) // and this is not THIS file | |
.filter(stack => stack.indexOf('node_modules') < 0)[0]; // and not node_modules (aka Jest internals) | |
/**/ | |
// fake module parent | |
rewiremock.overrideEntryPoint({ | |
...module, | |
id: originalCaller, | |
filename: originalCaller | |
}); | |
} | |
// nodejs relative imports | |
addPlugin(plugins.relative); | |
let noCallThru = false; | |
const convertStubs = (stubs) => { | |
Object.keys(stubs).forEach(key => { | |
const stub = stubs[key]; | |
const mock = rewiremock(key) | |
.with(stub) | |
.directChildOnly() // emulate proxyquire behavior | |
.toBeUsed(); | |
.toMatchOrigin(); | |
// default is callthru | |
if (!noCallThru) { | |
mock.callThrough(); | |
} | |
}); | |
}; | |
const rewireproxy = (file, stubs) => rewireproxy.load(file, stubs); | |
rewireproxy.noCallThru = () => { | |
noCallThru = true; | |
return rewireproxy; | |
}; | |
// just fake it | |
rewireproxy.noPreserveCache = () => rewireproxy; | |
rewireproxy.load = (file, stubs) => { | |
let result = 0; | |
rewiremock.inScope(() => { | |
convertStubs(stubs); | |
result = rewiremock.proxy(file, {}); | |
}); | |
return result; | |
}; | |
export default rewireproxy; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment