index.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = void 0;
  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. 'require',
  86. 'undefined',
  87. ...Object.getOwnPropertyNames(global)
  88. ].sort()
  89. );
  90. const IDVisitor = {
  91. ReferencedIdentifier(path, {ids}) {
  92. ids.add(path);
  93. },
  94. blacklist: ['TypeAnnotation', 'TSTypeAnnotation', 'TSTypeReference']
  95. };
  96. const FUNCTIONS = Object.create(null);
  97. FUNCTIONS.mock = args => {
  98. if (args.length === 1) {
  99. return args[0].isStringLiteral() || args[0].isLiteral();
  100. } else if (args.length === 2 || args.length === 3) {
  101. const moduleFactory = args[1];
  102. if (!moduleFactory.isFunction()) {
  103. throw moduleFactory.buildCodeFrameError(
  104. 'The second argument of `jest.mock` must be an inline function.\n',
  105. TypeError
  106. );
  107. }
  108. const ids = new Set();
  109. const parentScope = moduleFactory.parentPath.scope; // @ts-expect-error: ReferencedIdentifier and blacklist are not known on visitors
  110. moduleFactory.traverse(IDVisitor, {
  111. ids
  112. });
  113. for (const id of ids) {
  114. const {name} = id.node;
  115. let found = false;
  116. let scope = id.scope;
  117. while (scope !== parentScope) {
  118. if (scope.bindings[name]) {
  119. found = true;
  120. break;
  121. }
  122. scope = scope.parent;
  123. }
  124. if (!found) {
  125. let isAllowedIdentifier =
  126. (scope.hasGlobal(name) && ALLOWED_IDENTIFIERS.has(name)) ||
  127. /^mock/i.test(name) || // Allow istanbul's coverage variable to pass.
  128. /^(?:__)?cov/.test(name);
  129. if (!isAllowedIdentifier) {
  130. const binding = scope.bindings[name];
  131. if (
  132. binding === null || binding === void 0
  133. ? void 0
  134. : binding.path.isVariableDeclarator()
  135. ) {
  136. const {node} = binding.path;
  137. const initNode = node.init;
  138. if (initNode && binding.constant && scope.isPure(initNode, true)) {
  139. hoistedVariables.add(node);
  140. isAllowedIdentifier = true;
  141. }
  142. }
  143. }
  144. if (!isAllowedIdentifier) {
  145. throw id.buildCodeFrameError(
  146. 'The module factory of `jest.mock()` is not allowed to ' +
  147. 'reference any out-of-scope variables.\n' +
  148. 'Invalid variable access: ' +
  149. name +
  150. '\n' +
  151. 'Allowed objects: ' +
  152. Array.from(ALLOWED_IDENTIFIERS).join(', ') +
  153. '.\n' +
  154. 'Note: This is a precaution to guard against uninitialized mock ' +
  155. 'variables. If it is ensured that the mock is required lazily, ' +
  156. 'variable names prefixed with `mock` (case insensitive) are permitted.\n',
  157. ReferenceError
  158. );
  159. }
  160. }
  161. }
  162. return true;
  163. }
  164. return false;
  165. };
  166. FUNCTIONS.unmock = args => args.length === 1 && args[0].isStringLiteral();
  167. FUNCTIONS.deepUnmock = args => args.length === 1 && args[0].isStringLiteral();
  168. FUNCTIONS.disableAutomock = FUNCTIONS.enableAutomock = args =>
  169. args.length === 0;
  170. const createJestObjectGetter = (0, _template().statement)`
  171. function GETTER_NAME() {
  172. const { JEST_GLOBALS_MODULE_JEST_EXPORT_NAME } = require("JEST_GLOBALS_MODULE_NAME");
  173. GETTER_NAME = () => JEST_GLOBALS_MODULE_JEST_EXPORT_NAME;
  174. return JEST_GLOBALS_MODULE_JEST_EXPORT_NAME;
  175. }
  176. `;
  177. const isJestObject = expression => {
  178. // global
  179. if (
  180. expression.isIdentifier() &&
  181. expression.node.name === JEST_GLOBAL_NAME &&
  182. !expression.scope.hasBinding(JEST_GLOBAL_NAME)
  183. ) {
  184. return true;
  185. } // import { jest } from '@jest/globals'
  186. if (
  187. expression.referencesImport(
  188. JEST_GLOBALS_MODULE_NAME,
  189. JEST_GLOBALS_MODULE_JEST_EXPORT_NAME
  190. )
  191. ) {
  192. return true;
  193. } // import * as JestGlobals from '@jest/globals'
  194. if (
  195. expression.isMemberExpression() &&
  196. !expression.node.computed &&
  197. expression.get('object').referencesImport(JEST_GLOBALS_MODULE_NAME, '*') &&
  198. expression.node.property.type === 'Identifier' &&
  199. expression.node.property.name === JEST_GLOBALS_MODULE_JEST_EXPORT_NAME
  200. ) {
  201. return true;
  202. }
  203. return false;
  204. };
  205. const extractJestObjExprIfHoistable = expr => {
  206. var _FUNCTIONS$propertyNa;
  207. if (!expr.isCallExpression()) {
  208. return null;
  209. }
  210. const callee = expr.get('callee');
  211. const args = expr.get('arguments');
  212. if (!callee.isMemberExpression() || callee.node.computed) {
  213. return null;
  214. }
  215. const object = callee.get('object');
  216. const property = callee.get('property');
  217. const propertyName = property.node.name;
  218. const jestObjExpr = isJestObject(object)
  219. ? object // The Jest object could be returned from another call since the functions are all chainable.
  220. : extractJestObjExprIfHoistable(object);
  221. if (!jestObjExpr) {
  222. return null;
  223. } // Important: Call the function check last
  224. // It might throw an error to display to the user,
  225. // which should only happen if we're already sure it's a call on the Jest object.
  226. const functionLooksHoistable =
  227. (_FUNCTIONS$propertyNa = FUNCTIONS[propertyName]) === null ||
  228. _FUNCTIONS$propertyNa === void 0
  229. ? void 0
  230. : _FUNCTIONS$propertyNa.call(FUNCTIONS, args);
  231. return functionLooksHoistable ? jestObjExpr : null;
  232. };
  233. /* eslint-disable sort-keys */
  234. var _default = () => ({
  235. pre({path: program}) {
  236. this.declareJestObjGetterIdentifier = () => {
  237. if (this.jestObjGetterIdentifier) {
  238. return this.jestObjGetterIdentifier;
  239. }
  240. this.jestObjGetterIdentifier = program.scope.generateUidIdentifier(
  241. 'getJestObj'
  242. );
  243. program.unshiftContainer('body', [
  244. createJestObjectGetter({
  245. GETTER_NAME: this.jestObjGetterIdentifier.name,
  246. JEST_GLOBALS_MODULE_JEST_EXPORT_NAME,
  247. JEST_GLOBALS_MODULE_NAME
  248. })
  249. ]);
  250. return this.jestObjGetterIdentifier;
  251. };
  252. },
  253. visitor: {
  254. ExpressionStatement(exprStmt) {
  255. const jestObjExpr = extractJestObjExprIfHoistable(
  256. exprStmt.get('expression')
  257. );
  258. if (jestObjExpr) {
  259. jestObjExpr.replaceWith(
  260. (0, _types().callExpression)(
  261. this.declareJestObjGetterIdentifier(),
  262. []
  263. )
  264. );
  265. }
  266. }
  267. },
  268. // in `post` to make sure we come after an import transform and can unshift above the `require`s
  269. post({path: program}) {
  270. const self = this;
  271. visitBlock(program);
  272. program.traverse({
  273. BlockStatement: visitBlock
  274. });
  275. function visitBlock(block) {
  276. // use a temporary empty statement instead of the real first statement, which may itself be hoisted
  277. const [varsHoistPoint, callsHoistPoint] = block.unshiftContainer('body', [
  278. (0, _types().emptyStatement)(),
  279. (0, _types().emptyStatement)()
  280. ]);
  281. block.traverse({
  282. CallExpression: visitCallExpr,
  283. VariableDeclarator: visitVariableDeclarator,
  284. // do not traverse into nested blocks, or we'll hoist calls in there out to this block
  285. // @ts-expect-error blacklist is not known
  286. blacklist: ['BlockStatement']
  287. });
  288. callsHoistPoint.remove();
  289. varsHoistPoint.remove();
  290. function visitCallExpr(callExpr) {
  291. var _self$jestObjGetterId;
  292. const {
  293. node: {callee}
  294. } = callExpr;
  295. if (
  296. (0, _types().isIdentifier)(callee) &&
  297. callee.name ===
  298. ((_self$jestObjGetterId = self.jestObjGetterIdentifier) === null ||
  299. _self$jestObjGetterId === void 0
  300. ? void 0
  301. : _self$jestObjGetterId.name)
  302. ) {
  303. const mockStmt = callExpr.getStatementParent();
  304. if (mockStmt) {
  305. const mockStmtParent = mockStmt.parentPath;
  306. if (mockStmtParent.isBlock()) {
  307. const mockStmtNode = mockStmt.node;
  308. mockStmt.remove();
  309. callsHoistPoint.insertBefore(mockStmtNode);
  310. }
  311. }
  312. }
  313. }
  314. function visitVariableDeclarator(varDecl) {
  315. if (hoistedVariables.has(varDecl.node)) {
  316. // should be assert function, but it's not. So let's cast below
  317. varDecl.parentPath.assertVariableDeclaration();
  318. const {kind, declarations} = varDecl.parent;
  319. if (declarations.length === 1) {
  320. varDecl.parentPath.remove();
  321. } else {
  322. varDecl.remove();
  323. }
  324. varsHoistPoint.insertBefore(
  325. (0, _types().variableDeclaration)(kind, [varDecl.node])
  326. );
  327. }
  328. }
  329. }
  330. }
  331. });
  332. /* eslint-enable */
  333. exports.default = _default;