Skip to content

Commit

Permalink
rewire methods as non-enumerable
Browse files Browse the repository at this point in the history
  • Loading branch information
bttmly committed Oct 25, 2014
1 parent 3e06f87 commit ad7056d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
25 changes: 20 additions & 5 deletions lib/rewire.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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") {
Expand All @@ -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.
Expand Down
12 changes: 12 additions & 0 deletions test/testModules/sharedTestCases.js
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand Down

0 comments on commit ad7056d

Please sign in to comment.