Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/twbs/rewire.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--lib/__get__.js6
-rw-r--r--lib/__set__.js4
-rw-r--r--lib/browserify/browserInit.js12
-rw-r--r--lib/browserify/browserifyMiddleware.js15
-rw-r--r--lib/browserify/browserifyRewire.js34
-rw-r--r--test/__get__.test.js12
-rw-r--r--test/__set__.test.js25
-rw-r--r--test/browserify.browserifyRewire.test.js111
-rw-r--r--test/browserify/index.html8
-rw-r--r--test/detectStrictMode.test.js8
-rw-r--r--test/testModules/moduleA.js58
-rw-r--r--test/testModules/moduleB.js60
-rw-r--r--test/testModules/sharedTestCases.js99
-rw-r--r--test/testModules/someOtherModule.js2
14 files changed, 222 insertions, 232 deletions
diff --git a/lib/__get__.js b/lib/__get__.js
index d8cdfe7..74e652f 100644
--- a/lib/__get__.js
+++ b/lib/__get__.js
@@ -11,11 +11,11 @@
*/
function __get__() {
arguments.varName = arguments[0];
- if (typeof arguments.varName !== "string" || arguments.varName.length === 0) {
+ if (arguments.varName && typeof arguments.varName === "string") {
+ return eval(arguments.varName);
+ } else {
throw new TypeError("__get__ expects a non-empty string");
}
-
- return eval(arguments.varName);
}
module.exports = __get__; \ No newline at end of file
diff --git a/lib/__set__.js b/lib/__set__.js
index 61e8f94..6e02727 100644
--- a/lib/__set__.js
+++ b/lib/__set__.js
@@ -20,7 +20,7 @@ function __set__() {
varName + " is not declared within the module.'); } ";
};
- if (typeof arguments[0] === "object") {
+ if (typeof arguments[0] === "object" && arguments.length === 1) {
arguments.env = arguments.varName;
if (!arguments.env || Array.isArray(arguments.env)) {
throw new TypeError("__set__ expects an object as env");
@@ -31,7 +31,7 @@ function __set__() {
arguments.src += arguments.checkExistsSrc(arguments.varName, arguments.varValue) + arguments.varName + " = arguments.env." + arguments.varName + ";";
}
}
- } else if (typeof arguments.varName === "string") {
+ } else if (typeof arguments.varName === "string" && arguments.length === 2) {
if (!arguments.varName) {
throw new TypeError("__set__ expects a non-empty string as a variable name");
}
diff --git a/lib/browserify/browserInit.js b/lib/browserify/browserInit.js
deleted file mode 100644
index b79005d..0000000
--- a/lib/browserify/browserInit.js
+++ /dev/null
@@ -1,12 +0,0 @@
-/**
- * This code gets injected at the end of the browserify bundle via b.append().
- */
-
-if (typeof window.browserifyRequire === "undefined") {
- // Saves the browserifyRequire under a new name. Necessary to call the original browserifyRequire within
- // a module where the variable name "require" is overridden by the module's internal require.
- window.browserifyRequire = require;
-} else {
- throw new Error("(rewire/browserify) Naming collision detected: window.browserifyRequire seems to be occupied.");
-}
-
diff --git a/lib/browserify/browserifyMiddleware.js b/lib/browserify/browserifyMiddleware.js
index 8fa564a..fb1887f 100644
--- a/lib/browserify/browserifyMiddleware.js
+++ b/lib/browserify/browserifyMiddleware.js
@@ -6,7 +6,6 @@ var setterSrc = require("../__set__.js").toString(),
getRewireRequires = require("./getRewireRequires.js"),
detectStrictMode = require("../detectStrictMode.js"),
- browserInit = fs.readFileSync(__dirname + "/browserInit.js", "utf8"),
injectionSrc = getInjectionSrc().replace(/\s+/g, " "); // strip out unnecessary spaces to be unobtrusive in the debug view
/**
@@ -30,6 +29,14 @@ function getInjectionSrc() {
}
function browserifyMiddleware(b) {
+
+ /**
+ * Gets called for every module. Injects special code so rewire is able to access private variables.
+ *
+ * @param {String} src
+ * @param {String} filename
+ * @return {String}
+ */
function injectRewire(src, filename) {
var rewireRequires;
@@ -67,12 +74,12 @@ function browserifyMiddleware(b) {
// The module src is wrapped inside a self-executing function.
// This is necessary to separate the module src from the preceding eval(importGlobalsSrc),
// because the module src can be in strict mode.
- // In strict mode eval() can only declare vars the current scope. In this case our setters
+ // In strict mode eval() can only declare vars in the current scope. In this case our setters
// and getters won't work.
// @see https://developer.mozilla.org/en/JavaScript/Strict_mode#Making_eval_and_arguments_simpler
"(function () {" +
- // If the module uses strict mode we must ensure that "use strict" stays at the beginning of the module.
+ // If the module uses strict mode we must ensure that "use strict" stays at the beginning of the function.
(detectStrictMode(src)? ' "use strict"; ': ' ') +
injectionSrc + "\n" +
@@ -86,8 +93,6 @@ function browserifyMiddleware(b) {
// Register file handler
b.register(".js", injectRewire);
- // Append rewire initialization at the end of the bundle
- b.append(browserInit);
return b;
}
diff --git a/lib/browserify/browserifyRewire.js b/lib/browserify/browserifyRewire.js
index 8e24c09..f5d8f90 100644
--- a/lib/browserify/browserifyRewire.js
+++ b/lib/browserify/browserifyRewire.js
@@ -1,6 +1,6 @@
-require("../browser/shims.js"); // some shims for older browsers that are used by rewire()
+require("../browser/shims.js"); // some shims for older browsers that are necessary for rewire()
-var browserifyRequire = window.browserifyRequire,
+var pathUtil = require("path"),
getImportGlobalsSrc = require("../getImportGlobalsSrc.js");
/**
@@ -60,15 +60,21 @@ function browserifyRewire(parentModulePath, path, cache) {
cache = true;
}
- // Normalize path with file extensions
- absPath = browserifyRequire.resolve(path, parentModulePath);
+ // Normalize path with file extensions
+ absPath = pathUtil.resolve(parentModulePath, path);
- // Delete the original module from the cache so the next call to browserifyRequre()
- // executes the module
- delete browserifyRequire.cache[absPath];
+ // Retrieve original module from cache
+ originalModule = require.cache[absPath];
- // Require module to trigger rewire.register()
- browserifyRequire(path, parentModulePath);
+ if (originalModule && cache) {
+ // Delete the original module from the cache so the next call to browserifyRequre()
+ // executes the module
+ delete require.cache[absPath];
+ }
+
+ // Require module to trigger rewire.register().
+ // Putting (require) in brackets hides it for browserify.
+ (require)(absPath);
// Get registry entry of the target module
registryEntry = registry[absPath];
@@ -84,9 +90,7 @@ function browserifyRewire(parentModulePath, path, cache) {
rewiredExports.__get__ = registryEntry.getter;
if (cache) {
- browserifyRequire.cache[absPath] = rewiredModule;
- } else {
- browserifyRequire.cache[absPath] = originalModule; // returning originalModule to the cache
+ require.cache[absPath] = rewiredModule;
}
// Store rewired modules for rewire.reset()
@@ -114,7 +118,7 @@ browserifyRewire.register = function (filename, module, setter, getter) {
* Deletes all rewired modules from the cache
*/
browserifyRewire.reset = function () {
- var cache = browserifyRequire.cache,
+ var cache = require.cache,
i,
absPath;
@@ -174,9 +178,9 @@ browserifyRewire.getProxy = function (internalRequire, dirname) {
/**
* Scans for global vars an returns an evalable string that declares all globals as a var.
* This way a global variable can be overridden by __set__ without changing the global instance.
- * It is
+ * It is executed each time again to include global variables that have been added later.
*
- * @type {String}
+ * @return {String}
*/
browserifyRewire.getImportGlobalsSrc = function () {
return getImportGlobalsSrc(['require','module','exports','__dirname','__filename','process']);
diff --git a/test/__get__.test.js b/test/__get__.test.js
index 53e909c..7c40bdb 100644
--- a/test/__get__.test.js
+++ b/test/__get__.test.js
@@ -7,7 +7,7 @@ var expect = require("expect.js"),
function expectError(ErrConstructor) {
return function expectReferenceError(err) {
- expect(err.constructor.name).to.be(ErrConstructor.name);
+ expect(err.constructor.name === ErrConstructor.name).to.be(true);
};
}
@@ -17,6 +17,7 @@ describe("__get__", function () {
beforeEach(function () {
moduleFake = {
+ __filename: "some/file.js",
myNumber: 0,
myObj: {}
};
@@ -25,11 +26,12 @@ describe("__get__", function () {
"__get__ = " + __get__.toString() + "; " +
"setNumber = function (value) { myNumber = value; }; " +
"setObj = function (value) { myObj = value; }; ",
- moduleFake
+ moduleFake,
+ __filename
);
});
it("should return the initial value", function () {
- expect(moduleFake.__get__("myNumber")).to.be(0);
+ expect(moduleFake.__get__("myNumber") === 0).to.be(true);
expect(moduleFake.__get__("myObj")).to.eql({});
});
it("should return the changed value of the number", function () {
@@ -37,8 +39,8 @@ describe("__get__", function () {
moduleFake.setNumber(2);
moduleFake.setObj(newObj);
- expect(moduleFake.__get__("myNumber")).to.be(2);
- expect(moduleFake.__get__("myObj")).to.be(newObj);
+ expect(moduleFake.__get__("myNumber") === 2).to.be(true);
+ expect(moduleFake.__get__("myObj") === newObj).to.be(true);
});
it("should throw a ReferenceError when getting not existing vars", function () {
expect(function () {
diff --git a/test/__set__.test.js b/test/__set__.test.js
index 28e3e8d..85a1d37 100644
--- a/test/__set__.test.js
+++ b/test/__set__.test.js
@@ -7,7 +7,7 @@ var expect = require("expect.js"),
function expectError(ErrConstructor) {
return function expectReferenceError(err) {
- expect(err.constructor.name).to.be(ErrConstructor.name);
+ expect(err.constructor.name === ErrConstructor.name).to.be(true);
};
}
@@ -35,31 +35,31 @@ describe("__set__", function () {
);
});
it("should set the new number when calling with varName, varValue", function () {
- expect(moduleFake.getNumber()).to.be(0);
+ expect(moduleFake.getNumber() === 0).to.be(true);
moduleFake.__set__("myNumber", 2);
- expect(moduleFake.getNumber()).to.be(2);
+ expect(moduleFake.getNumber() === 2).to.be(true);
});
it("should set the new object when calling with varName, varValue", function () {
var newObj = { hello: "hello" };
expect(moduleFake.getObj()).to.eql({});
moduleFake.__set__("myObj", newObj);
- expect(moduleFake.getObj()).to.be(newObj);
+ expect(moduleFake.getObj() === newObj).to.be(true);
});
it("should set the new number and the new obj when calling with an env-obj", function () {
var newObj = { hello: "hello" };
- expect(moduleFake.getNumber()).to.be(0);
+ expect(moduleFake.getNumber() === 0).to.be(true);
expect(moduleFake.getObj()).to.eql({});
moduleFake.__set__({
myNumber: 2,
myObj: newObj
});
- expect(moduleFake.getNumber()).to.be(2);
- expect(moduleFake.getObj()).to.be(newObj);
+ expect(moduleFake.getNumber() === 2).to.be(true);
+ expect(moduleFake.getObj() === newObj).to.be(true);
});
it("should return undefined", function () {
- expect(moduleFake.__set__("myNumber", 4)).to.be(undefined);
+ expect(moduleFake.__set__("myNumber", 4) === undefined).to.be(true);
});
it("should throw a ReferenceError when trying to set non-existing vars", function () {
expect(function () {
@@ -72,9 +72,6 @@ describe("__set__", function () {
});
}).to.throwException(expectReferenceError);
});
- it("should not clash with vars used within the set method", function () {
-
- });
it("should throw a TypeError when passing misfitting params", function () {
expect(function () {
moduleFake.__set__();
@@ -97,5 +94,11 @@ describe("__set__", function () {
expect(function () {
moduleFake.__set__(function () {});
}).to.throwException(expectTypeError);
+ expect(function () {
+ moduleFake.__set__({}, true); // misfitting number of params
+ }).to.throwException(expectTypeError);
+ expect(function () {
+ moduleFake.__set__("someVar"); // misfitting number of params
+ }).to.throwException(expectTypeError);
});
}); \ No newline at end of file
diff --git a/test/browserify.browserifyRewire.test.js b/test/browserify.browserifyRewire.test.js
index e52a50c..54f4ad1 100644
--- a/test/browserify.browserifyRewire.test.js
+++ b/test/browserify.browserifyRewire.test.js
@@ -18,102 +18,23 @@ function runInFakeBrowserContext(src, filename) {
after: after,
beforeEach: beforeEach,
afterEach: afterEach,
- setTimeout: setTimeout
+ setTimeout: setTimeout,
+ clearTimeout: clearTimeout,
+ setInterval: setInterval,
+ clearInterval: clearInterval,
+ parseFloat: parseFloat,
+ parseInt: parseInt,
+ encodeURIComponent: function () {},
+ decodeURIComponent: function () {},
+ document: {}
},
- console: console,
- setTimeout: setTimeout,
- clearTimeout: clearTimeout,
- setInterval: setInterval,
- clearInterval: clearInterval,
- parseFloat: parseFloat,
- parseInt: parseInt,
- encodeURIComponent: function () {},
- decodeURIComponent: function () {}
+ console: console
}, filename);
}
describe("browserifyRewire", function () {
before(require("./testHelpers/createFakePackageJSON.js"));
after(require("./testHelpers/removeFakePackageJSON.js"));
- it("should attach __set__ and __get__ to the exports-obj", function (done) {
- var pathToBrowserfiyRewire = pathUtil.resolve(__dirname, "../lib/browserify/browserifyRewire.js"),
- context,
- exportsObj = {},
- moduleObj = {exports: exportsObj},
- returnedObj,
- browserifyRewire;
-
- // Register with fake objects
- // Using null for objects that are not involved in this particular test
- function moduleA() {
- "use strict";
-
- browserifyRewire.register("/a.js", null, null, null);
- returnedObj = browserifyRewire("/a.js", "/b.js");
- }
-
- function moduleB() {
- "use strict";
-
- browserifyRewire.register("/b.js", moduleObj, setter, getter);
-
- return exportsObj;
- }
-
- function fakeResolve() {
- return "/b.js";
- }
-
- function fakeRequire(path, parentModulePath) {
- var module;
-
- if (path === "../browser/shims.js") {
- return;
- } else if (path === "../getImportGlobalsSrc.js") {
- return require("../lib/getImportGlobalsSrc.js");
- }
-
- module = moduleB();
-
- expect(path).to.be("/b.js");
- expect(parentModulePath).to.be("/a.js");
- fakeRequire.cache["/b.js"] = module;
-
- return module;
- }
- fakeRequire.resolve = fakeResolve;
- fakeRequire.cache = {};
-
- function setter() {}
- function getter() {}
-
- context = {
- module: {},
- console: console,
- window: {
- browserifyRequire: fakeRequire
- },
- require: fakeRequire
- };
-
- fs.readFile(pathToBrowserfiyRewire, "utf8", function onBrowserifyRewireRead(err, src) {
- vm.runInNewContext(src, context, pathToBrowserfiyRewire);
- browserifyRewire = context.module.exports;
-
- moduleA();
-
- expect(returnedObj.__set__).to.be(setter);
- expect(returnedObj.__get__).to.be(getter);
- // Because browserify does not create the module-object newly when executing the module
- // again we have to copy the module object deeply and store that copy in the
- // cache. Therefore we're checking here if the returned exports-object and the
- // cached module-object are an independent copy.
- expect(returnedObj).not.to.be(exportsObj);
- expect(context.window.browserifyRequire.cache["/b.js"]).not.to.be(moduleObj);
-
- done();
- });
- });
it("should run all sharedTestCases without exception", function () {
var b = browserify({debug: true}),
middleware = require("rewire").browserify,
@@ -122,19 +43,15 @@ describe("browserifyRewire", function () {
vmBundle;
b.use(middleware);
- b.require(__dirname + "/testModules/sharedTestCases.js");
+ b.addEntry(__dirname + "/testModules/sharedTestCases.js");
vmBundle = b.bundle();
browserBundle = vmBundle;
// Setup for mocha
- browserBundle += 'window.onload = function () {' +
- 'console.log("These tests will only work in all browsers with the console being opened");' +
- 'mocha.setup("bdd");' +
- 'window.browserifyRequire("/test/testModules/sharedTestCases.js");' +
- 'mocha.run();' +
- '};';
+ browserBundle = "function enableTests() {" + browserBundle + "}";
- vmBundle += 'window.browserifyRequire("/test/testModules/sharedTestCases.js");';
+ /*
+ vmBundle += 'window.browserifyRequire("/test/testModules/sharedTestCases.js");'; */
// Output for browser-testing
fs.writeFileSync(browserOutput, browserBundle, "utf8");
diff --git a/test/browserify/index.html b/test/browserify/index.html
index 8f869a5..d2ff012 100644
--- a/test/browserify/index.html
+++ b/test/browserify/index.html
@@ -5,5 +5,13 @@
<script src="bundle.js" type="text/javascript"></script>
</head>
<body>
+ <script type="text/javascript">
+ window.onload = function () {
+ console.log("These tests will only work in all browsers with the console open");
+ mocha.setup("bdd");
+ enableTests();
+ mocha.run();
+ };
+ </script>
<div id="mocha"></div>
</body> \ No newline at end of file
diff --git a/test/detectStrictMode.test.js b/test/detectStrictMode.test.js
index a154471..dad674c 100644
--- a/test/detectStrictMode.test.js
+++ b/test/detectStrictMode.test.js
@@ -3,11 +3,11 @@ var expect = require("expect.js"),
describe("detectStrictMode", function () {
it("should detect \"use strict\"; at the beginning of a string and ignore all whitespace before", function () {
- expect(detectStrictMode('"use strict";')).to.be(true);
- expect(detectStrictMode(' "use strict";')).to.be(true);
- expect(detectStrictMode(' \n "use strict";')).to.be(true);
+ expect(detectStrictMode('"use strict";') === true).to.be(true);
+ expect(detectStrictMode(' "use strict";') === true).to.be(true);
+ expect(detectStrictMode(' \n "use strict";') === true).to.be(true);
});
it("should not detect \"use strict\"; if it occurs in some nested function", function () {
- expect(detectStrictMode('function () {"use strict";}')).to.be(false);
+ expect(detectStrictMode('function () {"use strict";}') === false).to.be(true);
});
}); \ No newline at end of file
diff --git a/test/testModules/moduleA.js b/test/testModules/moduleA.js
index 1e14071..ba2116e 100644
--- a/test/testModules/moduleA.js
+++ b/test/testModules/moduleA.js
@@ -52,41 +52,43 @@ function checkSomeGlobals() {
if (typeof __filename !== "string") {
throw new ReferenceError("__filename is not a string");
}
- //TODO add accurate checks here
- if (typeof setTimeout === "undefined") {
- throw new ReferenceError("setTimeout is undefined");
+ if (typeof setTimeout !== "function") {
+ throw new ReferenceError("setTimeout is not a function");
}
- if (typeof clearTimeout === "undefined") {
- throw new ReferenceError("clearTimeout is undefined");
+ if (typeof clearTimeout !== "function") {
+ throw new ReferenceError("clearTimeout is not a function");
}
- if (typeof setInterval === "undefined") {
- throw new ReferenceError("setInterval is undefined");
+ if (typeof setInterval !== "function") {
+ throw new ReferenceError("setInterval is not a function");
}
- if (typeof clearInterval === "undefined") {
- throw new ReferenceError("clearInterval is undefined");
+ if (typeof clearInterval !== "function") {
+ throw new ReferenceError("clearInterval is not a function");
}
- if (typeof Error === "undefined") {
- throw new ReferenceError("Error is undefined");
+ if (typeof Error !== "function") {
+ throw new ReferenceError("Error is not a function");
}
- if (typeof parseFloat === "undefined") {
- throw new ReferenceError("parseFloat is undefined");
+ if (typeof parseFloat !== "function") {
+ throw new ReferenceError("parseFloat is not a function");
}
- if (typeof parseInt === "undefined") {
- throw new ReferenceError("parseInt is undefined");
+ if (typeof parseInt !== "function") {
+ throw new ReferenceError("parseInt is not a function");
}
if (typeof window === "undefined") {
- if (typeof process === "undefined") {
- throw new ReferenceError("process is undefined");
+ if (typeof process !== "object") {
+ throw new ReferenceError("process is not an object");
}
- if (typeof Buffer === "undefined") {
- throw new ReferenceError("Buffer is undefined");
+ if (typeof Buffer !== "function") {
+ throw new ReferenceError("Buffer is not a function");
}
} else {
- if (typeof encodeURIComponent === "undefined") {
- throw new ReferenceError("encodeURIComponent is undefined");
+ if (typeof encodeURIComponent !== "function") {
+ throw new ReferenceError("encodeURIComponent is not a function");
}
- if (typeof decodeURIComponent === "undefined") {
- throw new ReferenceError("decodeURIComponent is undefined");
+ if (typeof decodeURIComponent !== "function") {
+ throw new ReferenceError("decodeURIComponent is not a function");
+ }
+ if (typeof document !== "object") {
+ throw new ReferenceError("document is not an object");
}
}
}
@@ -99,6 +101,14 @@ function getFilename() {
return __filename;
}
+function getBuffer() {
+ return Buffer;
+}
+
+function getDocument() {
+ return document;
+}
+
// different styles of exports in moduleA.js and moduleB.js
exports.setMyNumber = setMyNumber;
exports.getMyNumber = getMyNumber;
@@ -108,4 +118,6 @@ exports.readFileSync = readFileSync;
exports.checkSomeGlobals = checkSomeGlobals;
exports.getConsole = getConsole;
exports.getFilename = getFilename;
+exports.getBuffer = getBuffer;
+exports.getDocument = getDocument;
exports.someOtherModule = someOtherModule; \ No newline at end of file
diff --git a/test/testModules/moduleB.js b/test/testModules/moduleB.js
index b7646bd..9f7a1c7 100644
--- a/test/testModules/moduleB.js
+++ b/test/testModules/moduleB.js
@@ -44,7 +44,7 @@ function checkSomeGlobals() {
throw new ReferenceError("exports is not an object");
}
if (module.exports === exports) {
- throw new Error("module.exports === exports returns true"); // should be false because we're setting module.exports at the bottom of this file
+ throw new Error("module.exports === exports returns true"); // because we're exporting via module.exports they should not be the same.
}
if (typeof __dirname !== "string") {
throw new ReferenceError("__dirname is not a string");
@@ -52,41 +52,43 @@ function checkSomeGlobals() {
if (typeof __filename !== "string") {
throw new ReferenceError("__filename is not a string");
}
- //TODO add accurate checks here
- if (typeof setTimeout === "undefined") {
- throw new ReferenceError("setTimeout is undefined");
+ if (typeof setTimeout !== "function") {
+ throw new ReferenceError("setTimeout is not a function");
}
- if (typeof clearTimeout === "undefined") {
- throw new ReferenceError("clearTimeout is undefined");
+ if (typeof clearTimeout !== "function") {
+ throw new ReferenceError("clearTimeout is not a function");
}
- if (typeof setInterval === "undefined") {
- throw new ReferenceError("setInterval is undefined");
+ if (typeof setInterval !== "function") {
+ throw new ReferenceError("setInterval is not a function");
}
- if (typeof clearInterval === "undefined") {
- throw new ReferenceError("clearInterval is undefined");
+ if (typeof clearInterval !== "function") {
+ throw new ReferenceError("clearInterval is not a function");
}
- if (typeof Error === "undefined") {
- throw new ReferenceError("Error is undefined");
+ if (typeof Error !== "function") {
+ throw new ReferenceError("Error is not a function");
}
- if (typeof parseFloat === "undefined") {
- throw new ReferenceError("parseFloat is undefined");
+ if (typeof parseFloat !== "function") {
+ throw new ReferenceError("parseFloat is not a function");
}
- if (typeof parseInt === "undefined") {
- throw new ReferenceError("parseInt is undefined");
+ if (typeof parseInt !== "function") {
+ throw new ReferenceError("parseInt is not a function");
}
if (typeof window === "undefined") {
- if (typeof process === "undefined") {
- throw new ReferenceError("process is undefined");
+ if (typeof process !== "object") {
+ throw new ReferenceError("process is not an object");
}
- if (typeof Buffer === "undefined") {
- throw new ReferenceError("Buffer is undefined");
+ if (typeof Buffer !== "function") {
+ throw new ReferenceError("Buffer is not a function");
}
} else {
- if (typeof encodeURIComponent === "undefined") {
- throw new ReferenceError("encodeURIComponent is undefined");
+ if (typeof encodeURIComponent !== "function") {
+ throw new ReferenceError("encodeURIComponent is not a function");
}
- if (typeof decodeURIComponent === "undefined") {
- throw new ReferenceError("decodeURIComponent is undefined");
+ if (typeof decodeURIComponent !== "function") {
+ throw new ReferenceError("decodeURIComponent is not a function");
+ }
+ if (typeof document !== "object") {
+ throw new ReferenceError("document is not an object");
}
}
}
@@ -99,6 +101,14 @@ function getFilename() {
return __filename;
}
+function getBuffer() {
+ return Buffer;
+}
+
+function getDocument() {
+ return document;
+}
+
// different styles of exports in moduleA.js and moduleB.js
module.exports = {
setMyNumber: setMyNumber,
@@ -109,5 +119,7 @@ module.exports = {
checkSomeGlobals: checkSomeGlobals,
getConsole: getConsole,
getFilename: getFilename,
+ getBuffer: getBuffer,
+ getDocument: getDocument,
someOtherModule: someOtherModule
};
diff --git a/test/testModules/sharedTestCases.js b/test/testModules/sharedTestCases.js
index 5f0a78b..7c6c253 100644
--- a/test/testModules/sharedTestCases.js
+++ b/test/testModules/sharedTestCases.js
@@ -16,7 +16,7 @@ var testModules = {
function checkForTypeError(err) {
- expect(err.constructor).to.be(TypeError);
+ expect(err.constructor === TypeError).to.be(true);
}
function cleanRequireCache() {
@@ -34,11 +34,11 @@ function cleanRequireCache() {
describe("rewire " + (typeof window === "undefined"? "(node.js)": "(browser)"), function () {
afterEach(cleanRequireCache); // ensuring a clean test environment
it("should work like require()", function () {
- expect(rewire("./moduleA.js")).to.be(require("./moduleA.js"));
+ expect(rewire("./moduleA.js") === require("./moduleA.js")).to.be(true);
cleanRequireCache();
- expect(rewire("../testModules/moduleA.js")).to.be(require("../testModules/moduleA.js"));
+ expect(rewire("../testModules/moduleA.js") === require("../testModules/moduleA.js")).to.be(true);
cleanRequireCache();
- expect(rewire("./moduleA.js")).to.be(require("./moduleA.js"));
+ expect(rewire("./moduleA.js") === require("./moduleA.js")).to.be(true);
});
it("should modify the module so it provides a __set__ - function", function () {
expect(rewire("./moduleA.js").__set__).to.be.a(Function);
@@ -51,10 +51,10 @@ describe("rewire " + (typeof window === "undefined"? "(node.js)": "(browser)"),
it("should not influence other modules", function () {
var rewiredModuleA = rewire("./moduleA.js");
- expect(require("./someOtherModule.js").__set__).to.be(undefined);
- expect(require("./someOtherModule.js").__get__).to.be(undefined);
- expect(require("fs").__set__).to.be(undefined);
- expect(require("fs").__get__).to.be(undefined);
+ expect(require("./someOtherModule.js").__set__ === undefined).to.be(true);
+ expect(require("./someOtherModule.js").__get__ === undefined).to.be(true);
+ expect(require("fs").__set__ === undefined).to.be(true);
+ expect(require("fs").__get__ === undefined).to.be(true);
});
it("should not override/influence global objects by default", function () {
// This should throw no exception
@@ -65,24 +65,24 @@ describe("rewire " + (typeof window === "undefined"? "(node.js)": "(browser)"),
var rewiredModuleA = rewire("./moduleA.js"),
newObj = {};
- expect(rewiredModuleA.getMyNumber()).to.be(0);
+ expect(rewiredModuleA.getMyNumber() === 0).to.be(true);
rewiredModuleA.__set__("myNumber", 2);
- expect(rewiredModuleA.getMyNumber()).to.be(2);
+ expect(rewiredModuleA.getMyNumber() === 2).to.be(true);
rewiredModuleA.__set__("myObj", newObj);
- expect(rewiredModuleA.getMyObj()).to.be(newObj);
+ expect(rewiredModuleA.getMyObj() === newObj).to.be(true);
rewiredModuleA.__set__("env", "ENVENV");
});
it("should provide the ability to get private vars", function () {
var rewiredModuleA = rewire("./moduleA.js");
- expect(rewiredModuleA.__get__("myNumber")).to.be(rewiredModuleA.getMyNumber());
- expect(rewiredModuleA.__get__("myObj")).to.be(rewiredModuleA.getMyObj());
+ expect(rewiredModuleA.__get__("myNumber") === rewiredModuleA.getMyNumber()).to.be(true);
+ expect(rewiredModuleA.__get__("myObj") === rewiredModuleA.getMyObj()).to.be(true);
});
it("should provide the ability to inject mocks", function (done) {
var rewiredModuleA = rewire("./moduleA.js"),
mockedFs = {
readFileSync: function (file) {
- expect(file).to.be("bla.txt");
+ expect(file === "bla.txt").to.be(true);
done();
}
};
@@ -97,46 +97,83 @@ describe("rewire " + (typeof window === "undefined"? "(node.js)": "(browser)"),
rewiredModuleA.__set__("fs", mockedFs);
someOtherModule = require("./someOtherModule.js");
- expect(someOtherModule.fs).not.to.be(mockedFs);
+ expect(someOtherModule.fs === mockedFs).to.be(false);
});
it("should provide the ability to mock global objects just within the module", function () {
var rewiredModuleA = rewire("./moduleA.js"),
rewiredModuleB = rewire("./moduleB.js"),
consoleMock = {},
+ bufferMock = {},
+ documentMock = {},
newFilename = "myFile.js";
rewiredModuleA.__set__({
console: consoleMock,
__filename: newFilename
});
- expect(rewiredModuleA.getConsole()).to.be(consoleMock);
- expect(rewiredModuleB.getConsole()).not.to.be(consoleMock);
- expect(console).not.to.be(consoleMock);
- expect(rewiredModuleA.getFilename()).to.be(newFilename);
- expect(rewiredModuleB.getFilename()).not.to.be(newFilename);
+ expect(rewiredModuleA.getConsole() === consoleMock).to.be(true);
+ expect(rewiredModuleB.getConsole() === consoleMock).to.be(false);
+ expect(console === consoleMock).to.be(false);
+ expect(rewiredModuleA.getFilename() === newFilename).to.be(true);
+ expect(rewiredModuleB.getFilename() === newFilename).to.be(false);
+ expect(console === newFilename).to.be(false);
+ if (typeof window === "undefined") {
+ rewiredModuleA.__set__("Buffer", bufferMock);
+ expect(rewiredModuleA.getBuffer() === bufferMock).to.be(true);
+ expect(rewiredModuleB.getBuffer() === bufferMock).to.be(false);
+ expect(Buffer === bufferMock).to.be(false);
+ } else {
+ rewiredModuleA.__set__("document", documentMock);
+ expect(rewiredModuleA.getDocument() === documentMock).to.be(true);
+ expect(rewiredModuleB.getDocument() === documentMock === false).to.be(true);
+ expect(document === documentMock === false).to.be(true);
+ }
+ });
+ it("should be possible to mock global objects that are added on runtime", function () {
+ var rewiredModule;
+
+ if (typeof window === "undefined") {
+ global.someGlobalVar = "test";
+ rewiredModule = rewire("./moduleA.js");
+ rewiredModule.__set__("someGlobalVar", "other value");
+ expect(global.someGlobalVar === "test").to.be(true);
+ expect(rewiredModule.__get__("someGlobalVar") === "other value").to.be(true);
+ delete global.someGlobalVar;
+ } else {
+ window.someGlobalVar = "test";
+ rewiredModule = rewire("./moduleA.js");
+ rewiredModule.__set__("someGlobalVar", "other value");
+ expect(window.someGlobalVar === "test").to.be(true);
+ expect(rewiredModule.__get__("someGlobalVar") === "other value").to.be(true);
+ delete window.someGlobalVar;
+ }
});
it("should cache the rewired module", function () {
var rewired;
rewired = rewire("./someOtherModule.js");
- expect(require("./moduleA.js").someOtherModule).to.be(rewired);
+ expect(require("./moduleA.js").someOtherModule === rewired).to.be(true);
cleanRequireCache();
rewired = rewire("./someOtherModule.js", true);
- expect(require("./moduleA.js").someOtherModule).to.be(rewired);
+ expect(require("./moduleA.js").someOtherModule === rewired).to.be(true);
});
it("should not cache the rewired module on demand", function () {
- var rewired;
+ var rewired,
+ someOtherModule = require("./someOtherModule.js");
+
+ someOtherModule.fs = "This has been changed";
rewired = rewire("./someOtherModule.js", false);
- expect(require("./moduleA.js").someOtherModule).not.to.be(rewired);
+ expect(require("./moduleA.js").someOtherModule === rewired).to.be(false);
+ expect(require("./moduleA.js").someOtherModule.fs === "This has been changed").to.be(true);
});
it("should not influence the original require if nothing has been required within the rewired module", function () {
rewire("./emptyModule.js"); // nothing happens here because emptyModule doesn't require anything
- expect(require("./moduleA.js").__set__).to.be(undefined); // if restoring the original node require didn't worked, the module would have a setter
+ expect(require("./moduleA.js").__set__ === undefined).to.be(true); // if restoring the original node require didn't worked, the module would have a setter
});
it("subsequent calls of rewire should always return a new instance", function () {
- expect(rewire("./moduleA.js")).not.to.be(rewire("./moduleA.js"));
+ expect(rewire("./moduleA.js") === rewire("./moduleA.js")).to.be(false);
});
it("should preserve the strict mode (not IE)", function () {
var strictModule = rewire("./strictModule.js");
@@ -151,18 +188,18 @@ describe("rewire " + (typeof window === "undefined"? "(node.js)": "(browser)"),
someOtherModule.fs = "This has been modified";
rewiredSomeOtherModule = rewire("./someOtherModule.js");
- expect(rewiredSomeOtherModule.fs).not.to.be("This has been modified");
+ expect(rewiredSomeOtherModule.fs === "This has been modified").to.be(false);
});
describe("#reset", function () {
it("should remove all rewired modules from cache", function () {
var rewiredModuleA = rewire("./moduleA.js"),
rewiredModuleB = rewire("./moduleB.js");
- expect(require("./moduleA.js")).to.be(rewiredModuleA);
- expect(require("./moduleB.js")).to.be(rewiredModuleB);
+ expect(require("./moduleA.js") === rewiredModuleA).to.be(true);
+ expect(require("./moduleB.js") === rewiredModuleB).to.be(true);
rewire.reset();
- expect(require("./moduleA.js")).not.to.be(rewiredModuleA);
- expect(require("./moduleB.js")).not.to.be(rewiredModuleB);
+ expect(require("./moduleA.js") === rewiredModuleA).to.be(false);
+ expect(require("./moduleB.js") === rewiredModuleB).to.be(false);
});
});
}); \ No newline at end of file
diff --git a/test/testModules/someOtherModule.js b/test/testModules/someOtherModule.js
index 02287d1..bb86cd3 100644
--- a/test/testModules/someOtherModule.js
+++ b/test/testModules/someOtherModule.js
@@ -1,5 +1,7 @@
"use strict"; // run code in ES5 strict mode
+__filename = "/test/testModules/someOtherModule.js"; // unifying filename for the pretty stack trace test
+
var fs = require("fs");
exports.fs = fs; \ No newline at end of file