@@ -14,10 +14,12 @@ function invariant(condition, message) {
1414 }
1515}
1616
17- // We allow `jest`, `require`, all default Node.js globals and all ES2015
18- // built-ins to be used inside of a `jest.mock` factory.
17+ // We allow `jest`, `expect`, `require`, all default Node.js globals and all
18+ // ES2015 built-ins to be used inside of a `jest.mock` factory.
19+ // We also allow variables prefixed with `mock` as an escape-hatch.
1920const WHITELISTED_IDENTIFIERS = {
2021 jest : true ,
22+ expect : true ,
2123 require : true ,
2224 Infinity : true ,
2325 NaN : true ,
@@ -103,12 +105,16 @@ FUNCTIONS.mock = args => {
103105
104106 if ( ! found ) {
105107 invariant (
106- scope . hasGlobal ( name ) && WHITELISTED_IDENTIFIERS [ name ] ,
107- 'The second argument of `jest.mock()` is not allowed to ' +
108- 'reference any outside variables.\n' +
108+ ( scope . hasGlobal ( name ) && WHITELISTED_IDENTIFIERS [ name ] ) ||
109+ / ^ m o c k / . test ( name ) ,
110+ 'The module factory of `jest.mock()` is not allowed to ' +
111+ 'reference any out-of-scope variables.\n' +
109112 'Invalid variable access: ' + name + '\n' +
110113 'Whitelisted objects: ' +
111- Object . keys ( WHITELISTED_IDENTIFIERS ) . join ( ', ' ) + '.' ,
114+ Object . keys ( WHITELISTED_IDENTIFIERS ) . join ( ', ' ) + '.\n' +
115+ 'Note: This is a precaution to guard against uninitialized mock ' +
116+ 'variables. If it is ensured that the mock is required lazily, ' +
117+ 'variable names prefixed with `mock` are permitted.' ,
112118 ) ;
113119 }
114120 }
0 commit comments