12
12
function __set__ ( ) {
13
13
arguments . varName = arguments [ 0 ] ;
14
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
+ } ;
15
26
arguments . src = "" ;
16
27
arguments . revertArgs = [ ] ;
17
28
18
- if ( typeof arguments [ 0 ] === "object" && arguments . length === 1 ) {
29
+ if ( typeof arguments [ 0 ] === "object" ) {
19
30
arguments . env = arguments . varName ;
20
- if ( ! arguments . env || Array . isArray ( arguments . env ) ) {
21
- throw new TypeError ( "__set__ expects an object as env" ) ;
31
+ if ( ! arguments . env || arguments . refs . isArray ( arguments . env ) ) {
32
+ throw new arguments . refs . TypeError ( "__set__ expects an object as env" ) ;
22
33
}
23
34
arguments . revertArgs [ 0 ] = { } ;
24
35
for ( arguments . varName in arguments . env ) {
25
36
if ( arguments . env . hasOwnProperty ( arguments . varName ) ) {
26
37
arguments . varValue = arguments . env [ arguments . varName ] ;
27
- arguments . src += arguments . varName + " = arguments.env[" + JSON . stringify ( arguments . varName ) + "]; " ;
38
+ arguments . src += arguments . varName + " = arguments.env[" + arguments . refs . stringify ( arguments . varName ) + "]; " ;
28
39
try {
29
40
// Allow tests to mock implicit globals
30
41
//@see https://github.com/jhnns/rewire/issues/35
@@ -34,9 +45,9 @@ function __set__() {
34
45
}
35
46
}
36
47
}
37
- } else if ( typeof arguments . varName === "string" && arguments . length === 2 ) {
48
+ } else if ( typeof arguments . varName === "string" ) {
38
49
if ( ! arguments . varName ) {
39
- throw new TypeError ( "__set__ expects a non-empty string as a variable name" ) ;
50
+ throw new arguments . refs . TypeError ( "__set__ expects a non-empty string as a variable name" ) ;
40
51
}
41
52
arguments . src = arguments . varName + " = arguments.varValue;" ;
42
53
try {
@@ -47,9 +58,12 @@ function __set__() {
47
58
arguments . revertArgs = [ arguments . varName , undefined ] ;
48
59
}
49
60
} else {
50
- throw new TypeError ( "__set__ expects an environment object or a non-empty string as a variable name" ) ;
61
+ throw new arguments . refs . TypeError ( "__set__ expects an environment object or a non-empty string as a variable name" ) ;
51
62
}
52
63
64
+ // Passing our saved references on to the revert function
65
+ arguments . revertArgs [ 2 ] = arguments . refs ;
66
+
53
67
eval ( arguments . src ) ;
54
68
55
69
return function ( revertArgs ) {