UNPKG

3.14 kBJavaScriptView Raw
1/**
2 * This function will be stringified and then injected into every rewired module.
3 * Then you can set private variables by calling myModule.__set__("myPrivateVar", newValue);
4 *
5 * All variables within this function are namespaced in the arguments array because every
6 * var declaration could possibly clash with a variable in the module scope.
7 *
8 * @param {String|Object} varName name of the variable to set
9 * @param {String} varValue new value
10 * @return {Function}
11 */
12function __set__() {
13 arguments.varName = arguments[0];
14 arguments.varValue = arguments[1];
15 // Saving references to global objects and functions. Thus a test may even change these variables
16 // without interfering with rewire().
17 // @see https://github.com/jhnns/rewire/issues/40
18 arguments.refs = arguments[2] || {
19 isArray: Array.isArray,
20 TypeError: TypeError,
21 stringify: JSON.stringify
22 // We can't save eval() because eval() is a *special* global function
23 // That's why it can't be re-assigned in strict mode
24 //eval: eval
25 };
26 arguments.src = "";
27 arguments.revertArgs = [];
28
29 if (typeof arguments[0] === "object") {
30 arguments.env = arguments.varName;
31 if (!arguments.env || arguments.refs.isArray(arguments.env)) {
32 throw new arguments.refs.TypeError("__set__ expects an object as env");
33 }
34 arguments.revertArgs[0] = {};
35 for (arguments.varName in arguments.env) {
36 if (arguments.env.hasOwnProperty(arguments.varName)) {
37 arguments.varValue = arguments.env[arguments.varName];
38 arguments.src += arguments.varName + " = arguments.env[" + arguments.refs.stringify(arguments.varName) + "]; ";
39 try {
40 // Allow tests to mock implicit globals
41 // @see https://github.com/jhnns/rewire/issues/35
42 arguments.revertArgs[0][arguments.varName] = eval(arguments.varName);
43 } catch (err) {
44 arguments.revertArgs[0][arguments.varName] = undefined;
45 }
46 }
47 }
48 } else if (typeof arguments.varName === "string") {
49 if (!arguments.varName) {
50 throw new arguments.refs.TypeError("__set__ expects a non-empty string as a variable name");
51 }
52 arguments.src = arguments.varName + " = arguments.varValue;";
53 try {
54 // Allow tests to mock implicit globals
55 // @see https://github.com/jhnns/rewire/issues/35
56 arguments.revertArgs = [arguments.varName, eval(arguments.varName)];
57 } catch (err) {
58 arguments.revertArgs = [arguments.varName, undefined];
59 }
60 } else {
61 throw new arguments.refs.TypeError("__set__ expects an environment object or a non-empty string as a variable name");
62 }
63
64 // Passing our saved references on to the revert function
65 arguments.revertArgs[2] = arguments.refs;
66
67 eval(arguments.src);
68
69 return function (revertArgs) {
70 __set__.apply(null, revertArgs);
71 }.bind(null, arguments.revertArgs);
72}
73
74module.exports = __set__;