index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = jestHoist;
  6. function _template() {
  7. const data = require('@babel/template');
  8. _template = function () {
  9. return data;
  10. };
  11. return data;
  12. }
  13. function _types() {
  14. const data = require('@babel/types');
  15. _types = function () {
  16. return data;
  17. };
  18. return data;
  19. }
  20. /**
  21. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  22. *
  23. * This source code is licensed under the MIT license found in the
  24. * LICENSE file in the root directory of this source tree.
  25. *
  26. */
  27. const JEST_GLOBAL_NAME = 'jest';
  28. const JEST_GLOBALS_MODULE_NAME = '@jest/globals';
  29. const JEST_GLOBALS_MODULE_JEST_EXPORT_NAME = 'jest';
  30. const hoistedVariables = new WeakSet(); // We allow `jest`, `expect`, `require`, all default Node.js globals and all
  31. // ES2015 built-ins to be used inside of a `jest.mock` factory.
  32. // We also allow variables prefixed with `mock` as an escape-hatch.
  33. const ALLOWED_IDENTIFIERS = new Set(
  34. [
  35. 'Array',
  36. 'ArrayBuffer',
  37. 'Boolean',
  38. 'BigInt',
  39. 'DataView',
  40. 'Date',
  41. 'Error',
  42. 'EvalError',
  43. 'Float32Array',
  44. 'Float64Array',
  45. 'Function',
  46. 'Generator',
  47. 'GeneratorFunction',
  48. 'Infinity',
  49. 'Int16Array',
  50. 'Int32Array',
  51. 'Int8Array',
  52. 'InternalError',
  53. 'Intl',
  54. 'JSON',
  55. 'Map',
  56. 'Math',
  57. 'NaN',
  58. 'Number',
  59. 'Object',
  60. 'Promise',
  61. 'Proxy',
  62. 'RangeError',
  63. 'ReferenceError',
  64. 'Reflect',
  65. 'RegExp',
  66. 'Set',
  67. 'String',
  68. 'Symbol',
  69. 'SyntaxError',
  70. 'TypeError',
  71. 'URIError',
  72. 'Uint16Array',
  73. 'Uint32Array',
  74. 'Uint8Array',
  75. 'Uint8ClampedArray',
  76. 'WeakMap',
  77. 'WeakSet',
  78. 'arguments',
  79. 'console',
  80. 'expect',
  81. 'isNaN',
  82. 'jest',
  83. 'parseFloat',
  84. 'parseInt',
  85. 'exports',
  86. 'require',
  87. 'module',
  88. '__filename',
  89. '__dirname',
  90. 'undefined',
  91. ...Object.getOwnPropertyNames(global)
  92. ].sort()
  93. );
  94. const IDVisitor = {
  95. ReferencedIdentifier(path, {ids}) {
  96. ids.add(path);
  97. },
  98. blacklist: ['TypeAnnotation', 'TSTypeAnnotation', 'TSTypeReference']
  99. };
  100. const FUNCTIONS = Object.create(null);
  101. FUNCTIONS.mock = args => {
  102. if (args.length === 1) {
  103. return args[0].isStringLiteral() || args[0].isLiteral();
  104. } else if (args.length === 2 || args.length === 3) {
  105. const moduleFactory = args[1];
  106. if (!moduleFactory.isFunction()) {
  107. throw moduleFactory.buildCodeFrameError(
  108. 'The second argument of `jest.mock` must be an inline function.\n',
  109. TypeError
  110. );
  111. }
  112. const ids = new Set();
  113. const parentScope = moduleFactory.parentPath.scope; // @ts-expect-error: ReferencedIdentifier and blacklist are not known on visitors
  114. moduleFactory.traverse(IDVisitor, {
  115. ids
  116. });
  117. for (const id of ids) {
  118. const {name} = id.node;
  119. let found = false;
  120. let scope = id.scope;
  121. while (scope !== parentScope) {
  122. if (scope.bindings[name]) {
  123. found = true;
  124. break;
  125. }
  126. scope = scope.parent;
  127. }
  128. if (!found) {
  129. let isAllowedIdentifier =
  130. (scope.hasGlobal(name) && ALLOWED_IDENTIFIERS.has(name)) ||
  131. /^mock/i.test(name) || // Allow istanbul's coverage variable to pass.
  132. /^(?:__)?cov/.test(name);
  133. if (!isAllowedIdentifier) {
  134. const binding = scope.bindings[name];
  135. if (
  136. binding !== null &&
  137. binding !== void 0 &&
  138. binding.path.isVariableDeclarator()
  139. ) {
  140. const {node} = binding.path;
  141. const initNode = node.init;
  142. if (initNode && binding.constant && scope.isPure(initNode, true)) {
  143. hoistedVariables.add(node);
  144. isAllowedIdentifier = true;
  145. }
  146. }
  147. }
  148. if (!isAllowedIdentifier) {
  149. throw id.buildCodeFrameError(
  150. 'The module factory of `jest.mock()` is not allowed to ' +
  151. 'reference any out-of-scope variables.\n' +
  152. 'Invalid variable access: ' +
  153. name +
  154. '\n' +
  155. 'Allowed objects: ' +
  156. Array.from(ALLOWED_IDENTIFIERS).join(', ') +
  157. '.\n' +
  158. 'Note: This is a precaution to guard against uninitialized mock ' +
  159. 'variables. If it is ensured that the mock is required lazily, ' +
  160. 'variable names prefixed with `mock` (case insensitive) are permitted.\n',
  161. ReferenceError
  162. );
  163. }
  164. }
  165. }
  166. return true;
  167. }
  168. return false;
  169. };
  170. FUNCTIONS.unmock = args => args.length === 1 && args[0].isStringLiteral();
  171. FUNCTIONS.deepUnmock = args => args.length === 1 && args[0].isStringLiteral();
  172. FUNCTIONS.disableAutomock = FUNCTIONS.enableAutomock = args =>
  173. args.length === 0;
  174. const createJestObjectGetter = (0, _template().statement)`
  175. function GETTER_NAME() {
  176. const { JEST_GLOBALS_MODULE_JEST_EXPORT_NAME } = require("JEST_GLOBALS_MODULE_NAME");
  177. GETTER_NAME = () => JEST_GLOBALS_MODULE_JEST_EXPORT_NAME;
  178. return JEST_GLOBALS_MODULE_JEST_EXPORT_NAME;
  179. }
  180. `;
  181. const isJestObject = expression => {
  182. // global
  183. if (
  184. expression.isIdentifier() &&
  185. expression.node.name === JEST_GLOBAL_NAME &&
  186. !expression.scope.hasBinding(JEST_GLOBAL_NAME)
  187. ) {
  188. return true;
  189. } // import { jest } from '@jest/globals'
  190. if (
  191. expression.referencesImport(
  192. JEST_GLOBALS_MODULE_NAME,
  193. JEST_GLOBALS_MODULE_JEST_EXPORT_NAME
  194. )
  195. ) {
  196. return true;
  197. } // import * as JestGlobals from '@jest/globals'
  198. if (
  199. expression.isMemberExpression() &&
  200. !expression.node.computed &&
  201. expression.get('object').referencesImport(JEST_GLOBALS_MODULE_NAME, '*') &&
  202. expression.node.property.type === 'Identifier' &&
  203. expression.node.property.name === JEST_GLOBALS_MODULE_JEST_EXPORT_NAME
  204. ) {
  205. return true;
  206. }
  207. return false;
  208. };
  209. const extractJestObjExprIfHoistable = expr => {
  210. var _FUNCTIONS$propertyNa;
  211. if (!expr.isCallExpression()) {
  212. return null;
  213. }
  214. const callee = expr.get('callee');
  215. const args = expr.get('arguments');
  216. if (!callee.isMemberExpression() || callee.node.computed) {
  217. return null;
  218. }
  219. const object = callee.get('object');
  220. const property = callee.get('property');
  221. const propertyName = property.node.name;
  222. const jestObjExpr = isJestObject(object)
  223. ? object // The Jest object could be returned from another call since the functions are all chainable.
  224. : extractJestObjExprIfHoistable(object);
  225. if (!jestObjExpr) {
  226. return null;
  227. } // Important: Call the function check last
  228. // It might throw an error to display to the user,
  229. // which should only happen if we're already sure it's a call on the Jest object.
  230. const functionLooksHoistable =
  231. (_FUNCTIONS$propertyNa = FUNCTIONS[propertyName]) === null ||
  232. _FUNCTIONS$propertyNa === void 0
  233. ? void 0
  234. : _FUNCTIONS$propertyNa.call(FUNCTIONS, args);
  235. return functionLooksHoistable ? jestObjExpr : null;
  236. };
  237. /* eslint-disable sort-keys */
  238. function jestHoist() {
  239. return {
  240. pre({path: program}) {
  241. this.declareJestObjGetterIdentifier = () => {
  242. if (this.jestObjGetterIdentifier) {
  243. return this.jestObjGetterIdentifier;
  244. }
  245. this.jestObjGetterIdentifier =
  246. program.scope.generateUidIdentifier('getJestObj');
  247. program.unshiftContainer('body', [
  248. createJestObjectGetter({
  249. GETTER_NAME: this.jestObjGetterIdentifier.name,
  250. JEST_GLOBALS_MODULE_JEST_EXPORT_NAME,
  251. JEST_GLOBALS_MODULE_NAME
  252. })
  253. ]);
  254. return this.jestObjGetterIdentifier;
  255. };
  256. },
  257. visitor: {
  258. ExpressionStatement(exprStmt) {
  259. const jestObjExpr = extractJestObjExprIfHoistable(
  260. exprStmt.get('expression')
  261. );
  262. if (jestObjExpr) {
  263. jestObjExpr.replaceWith(
  264. (0, _types().callExpression)(
  265. this.declareJestObjGetterIdentifier(),
  266. []
  267. )
  268. );
  269. }
  270. }
  271. },
  272. // in `post` to make sure we come after an import transform and can unshift above the `require`s
  273. post({path: program}) {
  274. const self = this;
  275. visitBlock(program);
  276. program.traverse({
  277. BlockStatement: visitBlock
  278. });
  279. function visitBlock(block) {
  280. // use a temporary empty statement instead of the real first statement, which may itself be hoisted
  281. const [varsHoistPoint, callsHoistPoint] = block.unshiftContainer(
  282. 'body',
  283. [(0, _types().emptyStatement)(), (0, _types().emptyStatement)()]
  284. );
  285. block.traverse({
  286. CallExpression: visitCallExpr,
  287. VariableDeclarator: visitVariableDeclarator,
  288. // do not traverse into nested blocks, or we'll hoist calls in there out to this block
  289. blacklist: ['BlockStatement']
  290. });
  291. callsHoistPoint.remove();
  292. varsHoistPoint.remove();
  293. function visitCallExpr(callExpr) {
  294. var _self$jestObjGetterId;
  295. const {
  296. node: {callee}
  297. } = callExpr;
  298. if (
  299. (0, _types().isIdentifier)(callee) &&
  300. callee.name ===
  301. ((_self$jestObjGetterId = self.jestObjGetterIdentifier) ===
  302. null || _self$jestObjGetterId === void 0
  303. ? void 0
  304. : _self$jestObjGetterId.name)
  305. ) {
  306. const mockStmt = callExpr.getStatementParent();
  307. if (mockStmt) {
  308. const mockStmtParent = mockStmt.parentPath;
  309. if (mockStmtParent.isBlock()) {
  310. const mockStmtNode = mockStmt.node;
  311. mockStmt.remove();
  312. callsHoistPoint.insertBefore(mockStmtNode);
  313. }
  314. }
  315. }
  316. }
  317. function visitVariableDeclarator(varDecl) {
  318. if (hoistedVariables.has(varDecl.node)) {
  319. // should be assert function, but it's not. So let's cast below
  320. varDecl.parentPath.assertVariableDeclaration();
  321. const {kind, declarations} = varDecl.parent;
  322. if (declarations.length === 1) {
  323. varDecl.parentPath.remove();
  324. } else {
  325. varDecl.remove();
  326. }
  327. varsHoistPoint.insertBefore(
  328. (0, _types().variableDeclaration)(kind, [varDecl.node])
  329. );
  330. }
  331. }
  332. }
  333. }
  334. };
  335. }
  336. /* eslint-enable */