index.js 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define([], factory);
  6. else if(typeof exports === 'object')
  7. exports["jestMock"] = factory();
  8. else
  9. root["jestMock"] = factory();
  10. })(window, function() {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  50. /******/ }
  51. /******/ };
  52. /******/
  53. /******/ // define __esModule on exports
  54. /******/ __webpack_require__.r = function(exports) {
  55. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  56. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  57. /******/ }
  58. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  59. /******/ };
  60. /******/
  61. /******/ // create a fake namespace object
  62. /******/ // mode & 1: value is a module id, require it
  63. /******/ // mode & 2: merge all properties of value into the ns
  64. /******/ // mode & 4: return value when already ns object
  65. /******/ // mode & 8|1: behave like require
  66. /******/ __webpack_require__.t = function(value, mode) {
  67. /******/ if(mode & 1) value = __webpack_require__(value);
  68. /******/ if(mode & 8) return value;
  69. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  70. /******/ var ns = Object.create(null);
  71. /******/ __webpack_require__.r(ns);
  72. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  73. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  74. /******/ return ns;
  75. /******/ };
  76. /******/
  77. /******/ // getDefaultExport function for compatibility with non-harmony modules
  78. /******/ __webpack_require__.n = function(module) {
  79. /******/ var getter = module && module.__esModule ?
  80. /******/ function getDefault() { return module['default']; } :
  81. /******/ function getModuleExports() { return module; };
  82. /******/ __webpack_require__.d(getter, 'a', getter);
  83. /******/ return getter;
  84. /******/ };
  85. /******/
  86. /******/ // Object.prototype.hasOwnProperty.call
  87. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  88. /******/
  89. /******/ // __webpack_public_path__
  90. /******/ __webpack_require__.p = "";
  91. /******/
  92. /******/
  93. /******/ // Load entry module and return exports
  94. /******/ return __webpack_require__(__webpack_require__.s = "./packages/jest-mock/src/index.ts");
  95. /******/ })
  96. /************************************************************************/
  97. /******/ ({
  98. /***/ "./node_modules/webpack/buildin/global.js":
  99. /*!***********************************!*\
  100. !*** (webpack)/buildin/global.js ***!
  101. \***********************************/
  102. /*! no static exports found */
  103. /***/ (function(module, exports, __webpack_require__) {
  104. "use strict";
  105. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  106. var g; // This works in non-strict mode
  107. g = function () {
  108. return this;
  109. }();
  110. try {
  111. // This works if eval is allowed (see CSP)
  112. g = g || new Function("return this")();
  113. } catch (e) {
  114. // This works if the window reference is available
  115. if ((typeof window === "undefined" ? "undefined" : _typeof(window)) === "object") g = window;
  116. } // g can still be undefined, but nothing to do about it...
  117. // We return undefined, instead of nothing here, so it's
  118. // easier to handle this case. if(!global) { ...}
  119. module.exports = g;
  120. /***/ }),
  121. /***/ "./packages/jest-mock/src/index.ts":
  122. /*!*****************************************!*\
  123. !*** ./packages/jest-mock/src/index.ts ***!
  124. \*****************************************/
  125. /*! no static exports found */
  126. /***/ (function(module, exports, __webpack_require__) {
  127. "use strict";
  128. /* WEBPACK VAR INJECTION */(function(global) {
  129. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  130. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  131. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  132. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  133. /**
  134. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  135. *
  136. * This source code is licensed under the MIT license found in the
  137. * LICENSE file in the root directory of this source tree.
  138. */
  139. /**
  140. * Possible types of a MockFunctionResult.
  141. * 'return': The call completed by returning normally.
  142. * 'throw': The call completed by throwing a value.
  143. * 'incomplete': The call has not completed yet. This is possible if you read
  144. * the mock function result from within the mock function itself
  145. * (or a function called by the mock function).
  146. */
  147. /**
  148. * Represents the result of a single call to a mock function.
  149. */
  150. // see https://github.com/Microsoft/TypeScript/issues/25215
  151. var MOCK_CONSTRUCTOR_NAME = 'mockConstructor';
  152. var FUNCTION_NAME_RESERVED_PATTERN = /[\s!-\/:-@\[-`{-~]/;
  153. var FUNCTION_NAME_RESERVED_REPLACE = new RegExp(FUNCTION_NAME_RESERVED_PATTERN.source, 'g');
  154. var RESERVED_KEYWORDS = new Set(['arguments', 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'implements', 'import', 'in', 'instanceof', 'interface', 'let', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'static', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while', 'with', 'yield']);
  155. function matchArity(fn, length) {
  156. var mockConstructor;
  157. switch (length) {
  158. case 1:
  159. mockConstructor = function mockConstructor(_a) {
  160. return fn.apply(this, arguments);
  161. };
  162. break;
  163. case 2:
  164. mockConstructor = function mockConstructor(_a, _b) {
  165. return fn.apply(this, arguments);
  166. };
  167. break;
  168. case 3:
  169. mockConstructor = function mockConstructor(_a, _b, _c) {
  170. return fn.apply(this, arguments);
  171. };
  172. break;
  173. case 4:
  174. mockConstructor = function mockConstructor(_a, _b, _c, _d) {
  175. return fn.apply(this, arguments);
  176. };
  177. break;
  178. case 5:
  179. mockConstructor = function mockConstructor(_a, _b, _c, _d, _e) {
  180. return fn.apply(this, arguments);
  181. };
  182. break;
  183. case 6:
  184. mockConstructor = function mockConstructor(_a, _b, _c, _d, _e, _f) {
  185. return fn.apply(this, arguments);
  186. };
  187. break;
  188. case 7:
  189. mockConstructor = function mockConstructor(_a, _b, _c, _d, _e, _f, _g) {
  190. return fn.apply(this, arguments);
  191. };
  192. break;
  193. case 8:
  194. mockConstructor = function mockConstructor(_a, _b, _c, _d, _e, _f, _g, _h) {
  195. return fn.apply(this, arguments);
  196. };
  197. break;
  198. case 9:
  199. mockConstructor = function mockConstructor(_a, _b, _c, _d, _e, _f, _g, _h, _i) {
  200. return fn.apply(this, arguments);
  201. };
  202. break;
  203. default:
  204. mockConstructor = function mockConstructor() {
  205. return fn.apply(this, arguments);
  206. };
  207. break;
  208. }
  209. return mockConstructor;
  210. }
  211. function getObjectType(value) {
  212. return Object.prototype.toString.apply(value).slice(8, -1);
  213. }
  214. function getType(ref) {
  215. var typeName = getObjectType(ref);
  216. if (typeName === 'Function' || typeName === 'AsyncFunction' || typeName === 'GeneratorFunction') {
  217. return 'function';
  218. } else if (Array.isArray(ref)) {
  219. return 'array';
  220. } else if (typeName === 'Object') {
  221. return 'object';
  222. } else if (typeName === 'Number' || typeName === 'String' || typeName === 'Boolean' || typeName === 'Symbol') {
  223. return 'constant';
  224. } else if (typeName === 'Map' || typeName === 'WeakMap' || typeName === 'Set') {
  225. return 'collection';
  226. } else if (typeName === 'RegExp') {
  227. return 'regexp';
  228. } else if (ref === undefined) {
  229. return 'undefined';
  230. } else if (ref === null) {
  231. return 'null';
  232. } else {
  233. return null;
  234. }
  235. }
  236. function isReadonlyProp(object, prop) {
  237. if (prop === 'arguments' || prop === 'caller' || prop === 'callee' || prop === 'name' || prop === 'length') {
  238. var typeName = getObjectType(object);
  239. return typeName === 'Function' || typeName === 'AsyncFunction' || typeName === 'GeneratorFunction';
  240. }
  241. if (prop === 'source' || prop === 'global' || prop === 'ignoreCase' || prop === 'multiline') {
  242. return getObjectType(object) === 'RegExp';
  243. }
  244. return false;
  245. }
  246. var ModuleMockerClass =
  247. /*#__PURE__*/
  248. function () {
  249. /**
  250. * @see README.md
  251. * @param global Global object of the test environment, used to create
  252. * mocks
  253. */
  254. function ModuleMockerClass(global) {
  255. _classCallCheck(this, ModuleMockerClass);
  256. this._environmentGlobal = global;
  257. this._mockState = new WeakMap();
  258. this._mockConfigRegistry = new WeakMap();
  259. this._spyState = new Set();
  260. this.ModuleMocker = ModuleMockerClass;
  261. this._invocationCallCounter = 1;
  262. }
  263. _createClass(ModuleMockerClass, [{
  264. key: "_getSlots",
  265. value: function _getSlots(object) {
  266. if (!object) {
  267. return [];
  268. }
  269. var slots = new Set();
  270. var EnvObjectProto = this._environmentGlobal.Object.prototype;
  271. var EnvFunctionProto = this._environmentGlobal.Function.prototype;
  272. var EnvRegExpProto = this._environmentGlobal.RegExp.prototype; // Also check the builtins in the current context as they leak through
  273. // core node modules.
  274. var ObjectProto = Object.prototype;
  275. var FunctionProto = Function.prototype;
  276. var RegExpProto = RegExp.prototype; // Properties of Object.prototype, Function.prototype and RegExp.prototype
  277. // are never reported as slots
  278. while (object != null && object !== EnvObjectProto && object !== EnvFunctionProto && object !== EnvRegExpProto && object !== ObjectProto && object !== FunctionProto && object !== RegExpProto) {
  279. var ownNames = Object.getOwnPropertyNames(object);
  280. for (var i = 0; i < ownNames.length; i++) {
  281. var prop = ownNames[i];
  282. if (!isReadonlyProp(object, prop)) {
  283. var propDesc = Object.getOwnPropertyDescriptor(object, prop); // @ts-ignore Object.__esModule
  284. if (propDesc !== undefined && !propDesc.get || object.__esModule) {
  285. slots.add(prop);
  286. }
  287. }
  288. }
  289. object = Object.getPrototypeOf(object);
  290. }
  291. return Array.from(slots);
  292. }
  293. }, {
  294. key: "_ensureMockConfig",
  295. value: function _ensureMockConfig(f) {
  296. var config = this._mockConfigRegistry.get(f);
  297. if (!config) {
  298. config = this._defaultMockConfig();
  299. this._mockConfigRegistry.set(f, config);
  300. }
  301. return config;
  302. }
  303. }, {
  304. key: "_ensureMockState",
  305. value: function _ensureMockState(f) {
  306. var state = this._mockState.get(f);
  307. if (!state) {
  308. state = this._defaultMockState();
  309. this._mockState.set(f, state);
  310. }
  311. return state;
  312. }
  313. }, {
  314. key: "_defaultMockConfig",
  315. value: function _defaultMockConfig() {
  316. return {
  317. defaultReturnValue: undefined,
  318. isReturnValueLastSet: false,
  319. mockImpl: undefined,
  320. mockName: 'jest.fn()',
  321. specificMockImpls: [],
  322. specificReturnValues: []
  323. };
  324. }
  325. }, {
  326. key: "_defaultMockState",
  327. value: function _defaultMockState() {
  328. return {
  329. calls: [],
  330. instances: [],
  331. invocationCallOrder: [],
  332. results: []
  333. };
  334. }
  335. }, {
  336. key: "_makeComponent",
  337. value: function _makeComponent(metadata, restore) {
  338. var _this2 = this;
  339. if (metadata.type === 'object') {
  340. return new this._environmentGlobal.Object();
  341. } else if (metadata.type === 'array') {
  342. return new this._environmentGlobal.Array();
  343. } else if (metadata.type === 'regexp') {
  344. return new this._environmentGlobal.RegExp('');
  345. } else if (metadata.type === 'constant' || metadata.type === 'collection' || metadata.type === 'null' || metadata.type === 'undefined') {
  346. return metadata.value;
  347. } else if (metadata.type === 'function') {
  348. var prototype = metadata.members && metadata.members.prototype && metadata.members.prototype.members || {};
  349. var prototypeSlots = this._getSlots(prototype);
  350. var mocker = this;
  351. var mockConstructor = matchArity(function () {
  352. var _this = this,
  353. _arguments = arguments;
  354. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  355. args[_key] = arguments[_key];
  356. }
  357. var mockState = mocker._ensureMockState(f);
  358. var mockConfig = mocker._ensureMockConfig(f);
  359. mockState.instances.push(this);
  360. mockState.calls.push(args); // Create and record an "incomplete" mock result immediately upon
  361. // calling rather than waiting for the mock to return. This avoids
  362. // issues caused by recursion where results can be recorded in the
  363. // wrong order.
  364. var mockResult = {
  365. type: 'incomplete',
  366. value: undefined
  367. };
  368. mockState.results.push(mockResult);
  369. mockState.invocationCallOrder.push(mocker._invocationCallCounter++); // Will be set to the return value of the mock if an error is not thrown
  370. var finalReturnValue; // Will be set to the error that is thrown by the mock (if it throws)
  371. var thrownError; // Will be set to true if the mock throws an error. The presence of a
  372. // value in `thrownError` is not a 100% reliable indicator because a
  373. // function could throw a value of undefined.
  374. var callDidThrowError = false;
  375. try {
  376. // The bulk of the implementation is wrapped in an immediately
  377. // executed arrow function so the return value of the mock function
  378. // can be easily captured and recorded, despite the many separate
  379. // return points within the logic.
  380. finalReturnValue = function () {
  381. if (_this instanceof f) {
  382. // This is probably being called as a constructor
  383. prototypeSlots.forEach(function (slot) {
  384. // Copy prototype methods to the instance to make
  385. // it easier to interact with mock instance call and
  386. // return values
  387. if (prototype[slot].type === 'function') {
  388. // @ts-ignore no index signature
  389. var protoImpl = _this[slot]; // @ts-ignore no index signature
  390. _this[slot] = mocker.generateFromMetadata(prototype[slot]); // @ts-ignore no index signature
  391. _this[slot]._protoImpl = protoImpl;
  392. }
  393. }); // Run the mock constructor implementation
  394. var _mockImpl = mockConfig.specificMockImpls.length ? mockConfig.specificMockImpls.shift() : mockConfig.mockImpl;
  395. return _mockImpl && _mockImpl.apply(_this, _arguments);
  396. }
  397. var returnValue = mockConfig.defaultReturnValue; // If return value is last set, either specific or default, i.e.
  398. // mockReturnValueOnce()/mockReturnValue() is called and no
  399. // mockImplementationOnce()/mockImplementation() is called after
  400. // that.
  401. // use the set return value.
  402. if (mockConfig.specificReturnValues.length) {
  403. return mockConfig.specificReturnValues.shift();
  404. }
  405. if (mockConfig.isReturnValueLastSet) {
  406. return mockConfig.defaultReturnValue;
  407. } // If mockImplementationOnce()/mockImplementation() is last set,
  408. // or specific return values are used up, use the mock
  409. // implementation.
  410. var specificMockImpl;
  411. if (returnValue === undefined) {
  412. specificMockImpl = mockConfig.specificMockImpls.shift();
  413. if (specificMockImpl === undefined) {
  414. specificMockImpl = mockConfig.mockImpl;
  415. }
  416. if (specificMockImpl) {
  417. return specificMockImpl.apply(_this, _arguments);
  418. }
  419. } // Otherwise use prototype implementation
  420. if (returnValue === undefined && f._protoImpl) {
  421. return f._protoImpl.apply(_this, _arguments);
  422. }
  423. return returnValue;
  424. }();
  425. } catch (error) {
  426. // Store the thrown error so we can record it, then re-throw it.
  427. thrownError = error;
  428. callDidThrowError = true;
  429. throw error;
  430. } finally {
  431. // Record the result of the function.
  432. // NOTE: Intentionally NOT pushing/indexing into the array of mock
  433. // results here to avoid corrupting results data if mockClear()
  434. // is called during the execution of the mock.
  435. mockResult.type = callDidThrowError ? 'throw' : 'return';
  436. mockResult.value = callDidThrowError ? thrownError : finalReturnValue;
  437. }
  438. return finalReturnValue;
  439. }, metadata.length || 0);
  440. var f = this._createMockFunction(metadata, mockConstructor);
  441. f._isMockFunction = true;
  442. f.getMockImplementation = function () {
  443. return _this2._ensureMockConfig(f).mockImpl;
  444. };
  445. if (typeof restore === 'function') {
  446. this._spyState.add(restore);
  447. }
  448. this._mockState.set(f, this._defaultMockState());
  449. this._mockConfigRegistry.set(f, this._defaultMockConfig());
  450. Object.defineProperty(f, 'mock', {
  451. configurable: false,
  452. enumerable: true,
  453. get: function get() {
  454. return _this2._ensureMockState(f);
  455. },
  456. set: function set(val) {
  457. return _this2._mockState.set(f, val);
  458. }
  459. });
  460. f.mockClear = function () {
  461. _this2._mockState.delete(f);
  462. return f;
  463. };
  464. f.mockReset = function () {
  465. f.mockClear();
  466. _this2._mockConfigRegistry.delete(f);
  467. return f;
  468. };
  469. f.mockRestore = function () {
  470. f.mockReset();
  471. return restore ? restore() : undefined;
  472. };
  473. f.mockReturnValueOnce = function (value) {
  474. // next function call will return this value or default return value
  475. var mockConfig = _this2._ensureMockConfig(f);
  476. mockConfig.specificReturnValues.push(value);
  477. return f;
  478. };
  479. f.mockResolvedValueOnce = function (value) {
  480. return f.mockImplementationOnce(function () {
  481. return Promise.resolve(value);
  482. });
  483. };
  484. f.mockRejectedValueOnce = function (value) {
  485. return f.mockImplementationOnce(function () {
  486. return Promise.reject(value);
  487. });
  488. };
  489. f.mockReturnValue = function (value) {
  490. // next function call will return specified return value or this one
  491. var mockConfig = _this2._ensureMockConfig(f);
  492. mockConfig.isReturnValueLastSet = true;
  493. mockConfig.defaultReturnValue = value;
  494. return f;
  495. };
  496. f.mockResolvedValue = function (value) {
  497. return f.mockImplementation(function () {
  498. return Promise.resolve(value);
  499. });
  500. };
  501. f.mockRejectedValue = function (value) {
  502. return f.mockImplementation(function () {
  503. return Promise.reject(value);
  504. });
  505. };
  506. f.mockImplementationOnce = function (fn) {
  507. // next function call will use this mock implementation return value
  508. // or default mock implementation return value
  509. var mockConfig = _this2._ensureMockConfig(f);
  510. mockConfig.isReturnValueLastSet = false;
  511. mockConfig.specificMockImpls.push(fn);
  512. return f;
  513. };
  514. f.mockImplementation = function (fn) {
  515. // next function call will use mock implementation return value
  516. var mockConfig = _this2._ensureMockConfig(f);
  517. mockConfig.isReturnValueLastSet = false;
  518. mockConfig.defaultReturnValue = undefined;
  519. mockConfig.mockImpl = fn;
  520. return f;
  521. };
  522. f.mockReturnThis = function () {
  523. return f.mockImplementation(function () {
  524. return this;
  525. });
  526. };
  527. f.mockName = function (name) {
  528. if (name) {
  529. var mockConfig = _this2._ensureMockConfig(f);
  530. mockConfig.mockName = name;
  531. }
  532. return f;
  533. };
  534. f.getMockName = function () {
  535. var mockConfig = _this2._ensureMockConfig(f);
  536. return mockConfig.mockName || 'jest.fn()';
  537. };
  538. if (metadata.mockImpl) {
  539. f.mockImplementation(metadata.mockImpl);
  540. }
  541. return f;
  542. } else {
  543. var unknownType = metadata.type || 'undefined type';
  544. throw new Error('Unrecognized type ' + unknownType);
  545. }
  546. }
  547. }, {
  548. key: "_createMockFunction",
  549. value: function _createMockFunction(metadata, mockConstructor) {
  550. var name = metadata.name;
  551. if (!name) {
  552. return mockConstructor;
  553. } // Preserve `name` property of mocked function.
  554. var boundFunctionPrefix = 'bound ';
  555. var bindCall = ''; // if-do-while for perf reasons. The common case is for the if to fail.
  556. if (name && name.startsWith(boundFunctionPrefix)) {
  557. do {
  558. name = name.substring(boundFunctionPrefix.length); // Call bind() just to alter the function name.
  559. bindCall = '.bind(null)';
  560. } while (name && name.startsWith(boundFunctionPrefix));
  561. } // Special case functions named `mockConstructor` to guard for infinite
  562. // loops.
  563. if (name === MOCK_CONSTRUCTOR_NAME) {
  564. return mockConstructor;
  565. }
  566. if ( // It's a syntax error to define functions with a reserved keyword
  567. // as name.
  568. RESERVED_KEYWORDS.has(name) || // It's also a syntax error to define functions with a name that starts with a number
  569. /^\d/.test(name)) {
  570. name = '$' + name;
  571. } // It's also a syntax error to define a function with a reserved character
  572. // as part of it's name.
  573. if (FUNCTION_NAME_RESERVED_PATTERN.test(name)) {
  574. name = name.replace(FUNCTION_NAME_RESERVED_REPLACE, '$');
  575. }
  576. var body = 'return function ' + name + '() {' + 'return ' + MOCK_CONSTRUCTOR_NAME + '.apply(this,arguments);' + '}' + bindCall;
  577. var createConstructor = new this._environmentGlobal.Function(MOCK_CONSTRUCTOR_NAME, body);
  578. return createConstructor(mockConstructor);
  579. }
  580. }, {
  581. key: "_generateMock",
  582. value: function _generateMock(metadata, callbacks, refs) {
  583. var _this3 = this;
  584. // metadata not compatible but it's the same type, maybe problem with
  585. // overloading of _makeComponent and not _generateMock?
  586. // @ts-ignore
  587. var mock = this._makeComponent(metadata);
  588. if (metadata.refID != null) {
  589. refs[metadata.refID] = mock;
  590. }
  591. this._getSlots(metadata.members).forEach(function (slot) {
  592. var slotMetadata = metadata.members && metadata.members[slot] || {};
  593. if (slotMetadata.ref != null) {
  594. callbacks.push(function (ref) {
  595. return function () {
  596. return mock[slot] = refs[ref];
  597. };
  598. }(slotMetadata.ref));
  599. } else {
  600. mock[slot] = _this3._generateMock(slotMetadata, callbacks, refs);
  601. }
  602. });
  603. if (metadata.type !== 'undefined' && metadata.type !== 'null' && mock.prototype && _typeof(mock.prototype) === 'object') {
  604. mock.prototype.constructor = mock;
  605. }
  606. return mock;
  607. }
  608. /**
  609. * @see README.md
  610. * @param _metadata Metadata for the mock in the schema returned by the
  611. * getMetadata method of this module.
  612. */
  613. }, {
  614. key: "generateFromMetadata",
  615. value: function generateFromMetadata(_metadata) {
  616. var callbacks = [];
  617. var refs = {};
  618. var mock = this._generateMock(_metadata, callbacks, refs);
  619. callbacks.forEach(function (setter) {
  620. return setter();
  621. });
  622. return mock;
  623. }
  624. /**
  625. * @see README.md
  626. * @param component The component for which to retrieve metadata.
  627. */
  628. }, {
  629. key: "getMetadata",
  630. value: function getMetadata(component, _refs) {
  631. var _this4 = this;
  632. var refs = _refs || new Map();
  633. var ref = refs.get(component);
  634. if (ref != null) {
  635. return {
  636. ref: ref
  637. };
  638. }
  639. var type = getType(component);
  640. if (!type) {
  641. return null;
  642. }
  643. var metadata = {
  644. type: type
  645. };
  646. if (type === 'constant' || type === 'collection' || type === 'undefined' || type === 'null') {
  647. metadata.value = component;
  648. return metadata;
  649. } else if (type === 'function') {
  650. // @ts-ignore this is a function so it has a name
  651. metadata.name = component.name; // @ts-ignore may be a mock
  652. if (component._isMockFunction === true) {
  653. // @ts-ignore may be a mock
  654. metadata.mockImpl = component.getMockImplementation();
  655. }
  656. }
  657. metadata.refID = refs.size;
  658. refs.set(component, metadata.refID);
  659. var members = null; // Leave arrays alone
  660. if (type !== 'array') {
  661. this._getSlots(component).forEach(function (slot) {
  662. if (type === 'function' && // @ts-ignore may be a mock
  663. component._isMockFunction === true && slot.match(/^mock/)) {
  664. return;
  665. } // @ts-ignore no index signature
  666. var slotMetadata = _this4.getMetadata(component[slot], refs);
  667. if (slotMetadata) {
  668. if (!members) {
  669. members = {};
  670. }
  671. members[slot] = slotMetadata;
  672. }
  673. });
  674. }
  675. if (members) {
  676. metadata.members = members;
  677. }
  678. return metadata;
  679. }
  680. }, {
  681. key: "isMockFunction",
  682. value: function isMockFunction(fn) {
  683. return !!fn && fn._isMockFunction === true;
  684. }
  685. }, {
  686. key: "fn",
  687. value: function fn(implementation) {
  688. var length = implementation ? implementation.length : 0;
  689. var fn = this._makeComponent({
  690. length: length,
  691. type: 'function'
  692. });
  693. if (implementation) {
  694. fn.mockImplementation(implementation);
  695. }
  696. return fn;
  697. }
  698. }, {
  699. key: "spyOn",
  700. value: function spyOn(object, methodName, accessType) {
  701. if (accessType) {
  702. return this._spyOnProperty(object, methodName, accessType);
  703. }
  704. if (_typeof(object) !== 'object' && typeof object !== 'function') {
  705. throw new Error('Cannot spyOn on a primitive value; ' + this._typeOf(object) + ' given');
  706. }
  707. var original = object[methodName];
  708. if (!this.isMockFunction(original)) {
  709. if (typeof original !== 'function') {
  710. throw new Error('Cannot spy the ' + methodName + ' property because it is not a function; ' + this._typeOf(original) + ' given instead');
  711. }
  712. var isMethodOwner = object.hasOwnProperty(methodName); // @ts-ignore overriding original method with a Mock
  713. object[methodName] = this._makeComponent({
  714. type: 'function'
  715. }, function () {
  716. if (isMethodOwner) {
  717. object[methodName] = original;
  718. } else {
  719. delete object[methodName];
  720. }
  721. }); // @ts-ignore original method is now a Mock
  722. object[methodName].mockImplementation(function () {
  723. return original.apply(this, arguments);
  724. });
  725. }
  726. return object[methodName];
  727. }
  728. }, {
  729. key: "_spyOnProperty",
  730. value: function _spyOnProperty(obj, propertyName) {
  731. var accessType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'get';
  732. if (_typeof(obj) !== 'object' && typeof obj !== 'function') {
  733. throw new Error('Cannot spyOn on a primitive value; ' + this._typeOf(obj) + ' given');
  734. }
  735. if (!obj) {
  736. throw new Error('spyOn could not find an object to spy upon for ' + propertyName + '');
  737. }
  738. if (!propertyName) {
  739. throw new Error('No property name supplied');
  740. }
  741. var descriptor = Object.getOwnPropertyDescriptor(obj, propertyName);
  742. var proto = Object.getPrototypeOf(obj);
  743. while (!descriptor && proto !== null) {
  744. descriptor = Object.getOwnPropertyDescriptor(proto, propertyName);
  745. proto = Object.getPrototypeOf(proto);
  746. }
  747. if (!descriptor) {
  748. throw new Error(propertyName + ' property does not exist');
  749. }
  750. if (!descriptor.configurable) {
  751. throw new Error(propertyName + ' is not declared configurable');
  752. }
  753. if (!descriptor[accessType]) {
  754. throw new Error('Property ' + propertyName + ' does not have access type ' + accessType);
  755. }
  756. var original = descriptor[accessType];
  757. if (!this.isMockFunction(original)) {
  758. if (typeof original !== 'function') {
  759. throw new Error('Cannot spy the ' + propertyName + ' property because it is not a function; ' + this._typeOf(original) + ' given instead');
  760. } // @ts-ignore: mock is assignable
  761. descriptor[accessType] = this._makeComponent({
  762. type: 'function'
  763. }, function () {
  764. // @ts-ignore: mock is assignable
  765. descriptor[accessType] = original;
  766. Object.defineProperty(obj, propertyName, descriptor);
  767. });
  768. descriptor[accessType].mockImplementation(function () {
  769. // @ts-ignore
  770. return original.apply(this, arguments);
  771. });
  772. }
  773. Object.defineProperty(obj, propertyName, descriptor);
  774. return descriptor[accessType];
  775. }
  776. }, {
  777. key: "clearAllMocks",
  778. value: function clearAllMocks() {
  779. this._mockState = new WeakMap();
  780. }
  781. }, {
  782. key: "resetAllMocks",
  783. value: function resetAllMocks() {
  784. this._mockConfigRegistry = new WeakMap();
  785. this._mockState = new WeakMap();
  786. }
  787. }, {
  788. key: "restoreAllMocks",
  789. value: function restoreAllMocks() {
  790. this._spyState.forEach(function (restore) {
  791. return restore();
  792. });
  793. this._spyState = new Set();
  794. }
  795. }, {
  796. key: "_typeOf",
  797. value: function _typeOf(value) {
  798. return value == null ? '' + value : _typeof(value);
  799. }
  800. }]);
  801. return ModuleMockerClass;
  802. }();
  803. /* eslint-disable-next-line no-redeclare */
  804. var JestMock = new ModuleMockerClass(global);
  805. module.exports = JestMock;
  806. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js")))
  807. /***/ })
  808. /******/ });
  809. });
  810. //# sourceMappingURL=index.js.map