From ad7056daa37b376bdddd990ad117fdd271dbda8d Mon Sep 17 00:00:00 2001 From: Nick Bottomley Date: Fri, 24 Oct 2014 17:16:54 -0700 Subject: [PATCH] rewire methods as non-enumerable --- lib/rewire.js | 25 ++++++++++++++++++++----- test/testModules/sharedTestCases.js | 12 ++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/lib/rewire.js b/lib/rewire.js index 086cc27..29ad93f 100644 --- a/lib/rewire.js +++ b/lib/rewire.js @@ -9,7 +9,7 @@ var Module = require("module"), var __get__Src = __get__.toString(), __set__Src = __set__.toString(), - __with_Src = __with__.toString(); + __with__Src = __with__.toString(); /** * Does actual rewiring the module. For further documentation @see index.js @@ -18,7 +18,13 @@ function internalRewire(parentModulePath, targetPath) { var targetModule, prelude, appendix, - src; + srcs; + + srcs = { + "__get__": __get__Src, + "__set__": __set__Src, + "__with__": __with__Src + }; // Checking params if (typeof targetPath !== "string") { @@ -42,11 +48,20 @@ function internalRewire(parentModulePath, targetPath) { // We prepend a list of all globals declared with var so they can be overridden (without changing original globals) prelude = getImportGlobalsSrc(); + // We append our special setter and getter. appendix = "\n"; - appendix += "module.exports.__set__ = " + __set__Src + "; "; - appendix += "module.exports.__get__ = " + __get__Src + "; "; - appendix += "module.exports.__with__ = " + __with_Src + "; "; + + Object.keys(srcs).forEach( function (key) { + var str = [ + "Object.defineProperty(module.exports, '", + key, + "', {enumerable: false, value: ", + srcs[key], + "}); " + ].join(""); + appendix += str; + }); // Check if the module uses the strict mode. // If so we must ensure that "use strict"; stays at the beginning of the module. diff --git a/test/testModules/sharedTestCases.js b/test/testModules/sharedTestCases.js index 1ba1fae..9e667e3 100644 --- a/test/testModules/sharedTestCases.js +++ b/test/testModules/sharedTestCases.js @@ -66,6 +66,18 @@ describe("rewire " + (typeof testEnv === "undefined"? "(node)": "(" + testEnv + expect(rewire("./moduleB.js").__with__.toString()).to.be(__with__Src); }); + it("should provide __set__ as a non-enumerable property", function () { + expect(Object.keys(rewire("./moduleA.js")).indexOf("__set__")).to.be(-1) + }); + + it("should provide __get__ as a non-enumerable property", function () { + expect(Object.keys(rewire("./moduleA.js")).indexOf("__get__")).to.be(-1) + }); + + it("should provide __with__ as a non-enumerable property", function () { + expect(Object.keys(rewire("./moduleA.js")).indexOf("__with__")).to.be(-1) + }); + it("should not influence other modules", function () { rewire("./moduleA.js");