Skip to content

Instantly share code, notes, and snippets.

@theKashey
Created December 12, 2017 02:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theKashey/e42f283158455b640cddd12441074507 to your computer and use it in GitHub Desktop.
Save theKashey/e42f283158455b640cddd12441074507 to your computer and use it in GitHub Desktop.
"Proxyquire" inside the Jest
// 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