Skip to content

Instantly share code, notes, and snippets.

@sibelius
Created May 23, 2019 18:59
Show Gist options
  • Save sibelius/f98e62dd9346ddc97f07fe3814dc1b6e to your computer and use it in GitHub Desktop.
Save sibelius/f98e62dd9346ddc97f07fe3814dc1b6e to your computer and use it in GitHub Desktop.
Jest Runtime patch based on https://github.com/facebook/jest/pull/8331
diff --git a/node_modules/jest-runtime/build/index.js b/node_modules/jest-runtime/build/index.js
index b8ef341..746ef70 100644
--- a/node_modules/jest-runtime/build/index.js
+++ b/node_modules/jest-runtime/build/index.js
@@ -152,6 +152,8 @@ class Runtime {
_defineProperty(this, '_config', void 0);
+ _defineProperty(this, '_coreModulesProxyCache', void 0);
+
_defineProperty(this, '_coverageOptions', void 0);
_defineProperty(this, '_currentlyExecutingModulePath', void 0);
@@ -206,6 +208,7 @@ class Runtime {
collectCoverageFrom: [],
collectCoverageOnlyFrom: null
};
+ this._coreModulesProxyCache = Object.create(null);
this._currentlyExecutingModulePath = '';
this._environment = environment;
this._explicitShouldMock = Object.create(null);
@@ -863,9 +866,44 @@ class Runtime {
_requireCoreModule(moduleName) {
if (moduleName === 'process') {
return this._environment.global.process;
+ } // return require(moduleName);
+
+ const module = require(moduleName);
+
+ const freezeCoreModules = true;
+ const freezeCoreModulesWhitelist = ['crypto'];
+ const verbose = true;
+
+ if (!freezeCoreModules || freezeCoreModulesWhitelist.includes(moduleName)) {
+ return module;
+ }
+
+ if (this._coreModulesProxyCache[moduleName]) {
+ return this._coreModulesProxyCache[moduleName];
}
- return require(moduleName);
+ const set = (target, property, value, receiver) => {
+ if (typeof value !== 'function') {
+ return Reflect.set(target, property, value, receiver);
+ }
+
+ if (verbose) {
+ console.warn(
+ new (_jestUtil()).ErrorWithStack(
+ `Trying to override method '${property.toString()}' of a frozen core module '${moduleName}'`,
+ set
+ )
+ );
+ }
+
+ return true;
+ };
+
+ const proxy = new Proxy(module, {
+ set
+ });
+ this._coreModulesProxyCache[moduleName] = proxy;
+ return proxy;
}
_generateMock(from, moduleName) {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment