react-dom-test-utils.development.js 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741
  1. /**
  2. * @license React
  3. * react-dom-test-utils.development.js
  4. *
  5. * Copyright (c) Facebook, Inc. and its affiliates.
  6. *
  7. * This source code is licensed under the MIT license found in the
  8. * LICENSE file in the root directory of this source tree.
  9. */
  10. 'use strict';
  11. if (process.env.NODE_ENV !== "production") {
  12. (function() {
  13. 'use strict';
  14. var React = require('react');
  15. var ReactDOM = require('react-dom');
  16. var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  17. // by calls to these methods by a Babel plugin.
  18. //
  19. // In PROD (or in packages without access to React internals),
  20. // they are left as they are instead.
  21. function warn(format) {
  22. {
  23. {
  24. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  25. args[_key - 1] = arguments[_key];
  26. }
  27. printWarning('warn', format, args);
  28. }
  29. }
  30. }
  31. function error(format) {
  32. {
  33. {
  34. for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
  35. args[_key2 - 1] = arguments[_key2];
  36. }
  37. printWarning('error', format, args);
  38. }
  39. }
  40. }
  41. function printWarning(level, format, args) {
  42. // When changing this logic, you might want to also
  43. // update consoleWithStackDev.www.js as well.
  44. {
  45. var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
  46. var stack = ReactDebugCurrentFrame.getStackAddendum();
  47. if (stack !== '') {
  48. format += '%s';
  49. args = args.concat([stack]);
  50. } // eslint-disable-next-line react-internal/safe-string-coercion
  51. var argsWithFormat = args.map(function (item) {
  52. return String(item);
  53. }); // Careful: RN currently depends on this prefix
  54. argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
  55. // breaks IE9: https://github.com/facebook/react/issues/13610
  56. // eslint-disable-next-line react-internal/no-production-logging
  57. Function.prototype.apply.call(console[level], console, argsWithFormat);
  58. }
  59. }
  60. /**
  61. * `ReactInstanceMap` maintains a mapping from a public facing stateful
  62. * instance (key) and the internal representation (value). This allows public
  63. * methods to accept the user facing instance as an argument and map them back
  64. * to internal methods.
  65. *
  66. * Note that this module is currently shared and assumed to be stateless.
  67. * If this becomes an actual Map, that will break.
  68. */
  69. function get(key) {
  70. return key._reactInternals;
  71. }
  72. var FunctionComponent = 0;
  73. var ClassComponent = 1;
  74. var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
  75. var HostComponent = 5;
  76. var HostText = 6;
  77. // Don't change these two values. They're used by React Dev Tools.
  78. var NoFlags =
  79. /* */
  80. 0;
  81. var Placement =
  82. /* */
  83. 2;
  84. var Hydrating =
  85. /* */
  86. 4096;
  87. var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
  88. function getNearestMountedFiber(fiber) {
  89. var node = fiber;
  90. var nearestMounted = fiber;
  91. if (!fiber.alternate) {
  92. // If there is no alternate, this might be a new tree that isn't inserted
  93. // yet. If it is, then it will have a pending insertion effect on it.
  94. var nextNode = node;
  95. do {
  96. node = nextNode;
  97. if ((node.flags & (Placement | Hydrating)) !== NoFlags) {
  98. // This is an insertion or in-progress hydration. The nearest possible
  99. // mounted fiber is the parent but we need to continue to figure out
  100. // if that one is still mounted.
  101. nearestMounted = node.return;
  102. }
  103. nextNode = node.return;
  104. } while (nextNode);
  105. } else {
  106. while (node.return) {
  107. node = node.return;
  108. }
  109. }
  110. if (node.tag === HostRoot) {
  111. // TODO: Check if this was a nested HostRoot when used with
  112. // renderContainerIntoSubtree.
  113. return nearestMounted;
  114. } // If we didn't hit the root, that means that we're in an disconnected tree
  115. // that has been unmounted.
  116. return null;
  117. }
  118. function assertIsMounted(fiber) {
  119. if (getNearestMountedFiber(fiber) !== fiber) {
  120. throw new Error('Unable to find node on an unmounted component.');
  121. }
  122. }
  123. function findCurrentFiberUsingSlowPath(fiber) {
  124. var alternate = fiber.alternate;
  125. if (!alternate) {
  126. // If there is no alternate, then we only need to check if it is mounted.
  127. var nearestMounted = getNearestMountedFiber(fiber);
  128. if (nearestMounted === null) {
  129. throw new Error('Unable to find node on an unmounted component.');
  130. }
  131. if (nearestMounted !== fiber) {
  132. return null;
  133. }
  134. return fiber;
  135. } // If we have two possible branches, we'll walk backwards up to the root
  136. // to see what path the root points to. On the way we may hit one of the
  137. // special cases and we'll deal with them.
  138. var a = fiber;
  139. var b = alternate;
  140. while (true) {
  141. var parentA = a.return;
  142. if (parentA === null) {
  143. // We're at the root.
  144. break;
  145. }
  146. var parentB = parentA.alternate;
  147. if (parentB === null) {
  148. // There is no alternate. This is an unusual case. Currently, it only
  149. // happens when a Suspense component is hidden. An extra fragment fiber
  150. // is inserted in between the Suspense fiber and its children. Skip
  151. // over this extra fragment fiber and proceed to the next parent.
  152. var nextParent = parentA.return;
  153. if (nextParent !== null) {
  154. a = b = nextParent;
  155. continue;
  156. } // If there's no parent, we're at the root.
  157. break;
  158. } // If both copies of the parent fiber point to the same child, we can
  159. // assume that the child is current. This happens when we bailout on low
  160. // priority: the bailed out fiber's child reuses the current child.
  161. if (parentA.child === parentB.child) {
  162. var child = parentA.child;
  163. while (child) {
  164. if (child === a) {
  165. // We've determined that A is the current branch.
  166. assertIsMounted(parentA);
  167. return fiber;
  168. }
  169. if (child === b) {
  170. // We've determined that B is the current branch.
  171. assertIsMounted(parentA);
  172. return alternate;
  173. }
  174. child = child.sibling;
  175. } // We should never have an alternate for any mounting node. So the only
  176. // way this could possibly happen is if this was unmounted, if at all.
  177. throw new Error('Unable to find node on an unmounted component.');
  178. }
  179. if (a.return !== b.return) {
  180. // The return pointer of A and the return pointer of B point to different
  181. // fibers. We assume that return pointers never criss-cross, so A must
  182. // belong to the child set of A.return, and B must belong to the child
  183. // set of B.return.
  184. a = parentA;
  185. b = parentB;
  186. } else {
  187. // The return pointers point to the same fiber. We'll have to use the
  188. // default, slow path: scan the child sets of each parent alternate to see
  189. // which child belongs to which set.
  190. //
  191. // Search parent A's child set
  192. var didFindChild = false;
  193. var _child = parentA.child;
  194. while (_child) {
  195. if (_child === a) {
  196. didFindChild = true;
  197. a = parentA;
  198. b = parentB;
  199. break;
  200. }
  201. if (_child === b) {
  202. didFindChild = true;
  203. b = parentA;
  204. a = parentB;
  205. break;
  206. }
  207. _child = _child.sibling;
  208. }
  209. if (!didFindChild) {
  210. // Search parent B's child set
  211. _child = parentB.child;
  212. while (_child) {
  213. if (_child === a) {
  214. didFindChild = true;
  215. a = parentB;
  216. b = parentA;
  217. break;
  218. }
  219. if (_child === b) {
  220. didFindChild = true;
  221. b = parentB;
  222. a = parentA;
  223. break;
  224. }
  225. _child = _child.sibling;
  226. }
  227. if (!didFindChild) {
  228. throw new Error('Child was not found in either parent set. This indicates a bug ' + 'in React related to the return pointer. Please file an issue.');
  229. }
  230. }
  231. }
  232. if (a.alternate !== b) {
  233. throw new Error("Return fibers should always be each others' alternates. " + 'This error is likely caused by a bug in React. Please file an issue.');
  234. }
  235. } // If the root is not a host container, we're in a disconnected tree. I.e.
  236. // unmounted.
  237. if (a.tag !== HostRoot) {
  238. throw new Error('Unable to find node on an unmounted component.');
  239. }
  240. if (a.stateNode.current === a) {
  241. // We've determined that A is the current branch.
  242. return fiber;
  243. } // Otherwise B has to be current branch.
  244. return alternate;
  245. }
  246. var assign = Object.assign;
  247. /**
  248. * `charCode` represents the actual "character code" and is safe to use with
  249. * `String.fromCharCode`. As such, only keys that correspond to printable
  250. * characters produce a valid `charCode`, the only exception to this is Enter.
  251. * The Tab-key is considered non-printable and does not have a `charCode`,
  252. * presumably because it does not produce a tab-character in browsers.
  253. *
  254. * @param {object} nativeEvent Native browser event.
  255. * @return {number} Normalized `charCode` property.
  256. */
  257. function getEventCharCode(nativeEvent) {
  258. var charCode;
  259. var keyCode = nativeEvent.keyCode;
  260. if ('charCode' in nativeEvent) {
  261. charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`.
  262. if (charCode === 0 && keyCode === 13) {
  263. charCode = 13;
  264. }
  265. } else {
  266. // IE8 does not implement `charCode`, but `keyCode` has the correct value.
  267. charCode = keyCode;
  268. } // IE and Edge (on Windows) and Chrome / Safari (on Windows and Linux)
  269. // report Enter as charCode 10 when ctrl is pressed.
  270. if (charCode === 10) {
  271. charCode = 13;
  272. } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them.
  273. // Must not discard the (non-)printable Enter-key.
  274. if (charCode >= 32 || charCode === 13) {
  275. return charCode;
  276. }
  277. return 0;
  278. }
  279. function functionThatReturnsTrue() {
  280. return true;
  281. }
  282. function functionThatReturnsFalse() {
  283. return false;
  284. } // This is intentionally a factory so that we have different returned constructors.
  285. // If we had a single constructor, it would be megamorphic and engines would deopt.
  286. function createSyntheticEvent(Interface) {
  287. /**
  288. * Synthetic events are dispatched by event plugins, typically in response to a
  289. * top-level event delegation handler.
  290. *
  291. * These systems should generally use pooling to reduce the frequency of garbage
  292. * collection. The system should check `isPersistent` to determine whether the
  293. * event should be released into the pool after being dispatched. Users that
  294. * need a persisted event should invoke `persist`.
  295. *
  296. * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
  297. * normalizing browser quirks. Subclasses do not necessarily have to implement a
  298. * DOM interface; custom application-specific events can also subclass this.
  299. */
  300. function SyntheticBaseEvent(reactName, reactEventType, targetInst, nativeEvent, nativeEventTarget) {
  301. this._reactName = reactName;
  302. this._targetInst = targetInst;
  303. this.type = reactEventType;
  304. this.nativeEvent = nativeEvent;
  305. this.target = nativeEventTarget;
  306. this.currentTarget = null;
  307. for (var _propName in Interface) {
  308. if (!Interface.hasOwnProperty(_propName)) {
  309. continue;
  310. }
  311. var normalize = Interface[_propName];
  312. if (normalize) {
  313. this[_propName] = normalize(nativeEvent);
  314. } else {
  315. this[_propName] = nativeEvent[_propName];
  316. }
  317. }
  318. var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
  319. if (defaultPrevented) {
  320. this.isDefaultPrevented = functionThatReturnsTrue;
  321. } else {
  322. this.isDefaultPrevented = functionThatReturnsFalse;
  323. }
  324. this.isPropagationStopped = functionThatReturnsFalse;
  325. return this;
  326. }
  327. assign(SyntheticBaseEvent.prototype, {
  328. preventDefault: function () {
  329. this.defaultPrevented = true;
  330. var event = this.nativeEvent;
  331. if (!event) {
  332. return;
  333. }
  334. if (event.preventDefault) {
  335. event.preventDefault(); // $FlowFixMe - flow is not aware of `unknown` in IE
  336. } else if (typeof event.returnValue !== 'unknown') {
  337. event.returnValue = false;
  338. }
  339. this.isDefaultPrevented = functionThatReturnsTrue;
  340. },
  341. stopPropagation: function () {
  342. var event = this.nativeEvent;
  343. if (!event) {
  344. return;
  345. }
  346. if (event.stopPropagation) {
  347. event.stopPropagation(); // $FlowFixMe - flow is not aware of `unknown` in IE
  348. } else if (typeof event.cancelBubble !== 'unknown') {
  349. // The ChangeEventPlugin registers a "propertychange" event for
  350. // IE. This event does not support bubbling or cancelling, and
  351. // any references to cancelBubble throw "Member not found". A
  352. // typeof check of "unknown" circumvents this issue (and is also
  353. // IE specific).
  354. event.cancelBubble = true;
  355. }
  356. this.isPropagationStopped = functionThatReturnsTrue;
  357. },
  358. /**
  359. * We release all dispatched `SyntheticEvent`s after each event loop, adding
  360. * them back into the pool. This allows a way to hold onto a reference that
  361. * won't be added back into the pool.
  362. */
  363. persist: function () {// Modern event system doesn't use pooling.
  364. },
  365. /**
  366. * Checks if this event should be released back into the pool.
  367. *
  368. * @return {boolean} True if this should not be released, false otherwise.
  369. */
  370. isPersistent: functionThatReturnsTrue
  371. });
  372. return SyntheticBaseEvent;
  373. }
  374. /**
  375. * @interface Event
  376. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  377. */
  378. var EventInterface = {
  379. eventPhase: 0,
  380. bubbles: 0,
  381. cancelable: 0,
  382. timeStamp: function (event) {
  383. return event.timeStamp || Date.now();
  384. },
  385. defaultPrevented: 0,
  386. isTrusted: 0
  387. };
  388. var SyntheticEvent = createSyntheticEvent(EventInterface);
  389. var UIEventInterface = assign({}, EventInterface, {
  390. view: 0,
  391. detail: 0
  392. });
  393. var SyntheticUIEvent = createSyntheticEvent(UIEventInterface);
  394. var lastMovementX;
  395. var lastMovementY;
  396. var lastMouseEvent;
  397. function updateMouseMovementPolyfillState(event) {
  398. if (event !== lastMouseEvent) {
  399. if (lastMouseEvent && event.type === 'mousemove') {
  400. lastMovementX = event.screenX - lastMouseEvent.screenX;
  401. lastMovementY = event.screenY - lastMouseEvent.screenY;
  402. } else {
  403. lastMovementX = 0;
  404. lastMovementY = 0;
  405. }
  406. lastMouseEvent = event;
  407. }
  408. }
  409. /**
  410. * @interface MouseEvent
  411. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  412. */
  413. var MouseEventInterface = assign({}, UIEventInterface, {
  414. screenX: 0,
  415. screenY: 0,
  416. clientX: 0,
  417. clientY: 0,
  418. pageX: 0,
  419. pageY: 0,
  420. ctrlKey: 0,
  421. shiftKey: 0,
  422. altKey: 0,
  423. metaKey: 0,
  424. getModifierState: getEventModifierState,
  425. button: 0,
  426. buttons: 0,
  427. relatedTarget: function (event) {
  428. if (event.relatedTarget === undefined) return event.fromElement === event.srcElement ? event.toElement : event.fromElement;
  429. return event.relatedTarget;
  430. },
  431. movementX: function (event) {
  432. if ('movementX' in event) {
  433. return event.movementX;
  434. }
  435. updateMouseMovementPolyfillState(event);
  436. return lastMovementX;
  437. },
  438. movementY: function (event) {
  439. if ('movementY' in event) {
  440. return event.movementY;
  441. } // Don't need to call updateMouseMovementPolyfillState() here
  442. // because it's guaranteed to have already run when movementX
  443. // was copied.
  444. return lastMovementY;
  445. }
  446. });
  447. var SyntheticMouseEvent = createSyntheticEvent(MouseEventInterface);
  448. /**
  449. * @interface DragEvent
  450. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  451. */
  452. var DragEventInterface = assign({}, MouseEventInterface, {
  453. dataTransfer: 0
  454. });
  455. var SyntheticDragEvent = createSyntheticEvent(DragEventInterface);
  456. /**
  457. * @interface FocusEvent
  458. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  459. */
  460. var FocusEventInterface = assign({}, UIEventInterface, {
  461. relatedTarget: 0
  462. });
  463. var SyntheticFocusEvent = createSyntheticEvent(FocusEventInterface);
  464. /**
  465. * @interface Event
  466. * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface
  467. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent
  468. */
  469. var AnimationEventInterface = assign({}, EventInterface, {
  470. animationName: 0,
  471. elapsedTime: 0,
  472. pseudoElement: 0
  473. });
  474. var SyntheticAnimationEvent = createSyntheticEvent(AnimationEventInterface);
  475. /**
  476. * @interface Event
  477. * @see http://www.w3.org/TR/clipboard-apis/
  478. */
  479. var ClipboardEventInterface = assign({}, EventInterface, {
  480. clipboardData: function (event) {
  481. return 'clipboardData' in event ? event.clipboardData : window.clipboardData;
  482. }
  483. });
  484. var SyntheticClipboardEvent = createSyntheticEvent(ClipboardEventInterface);
  485. /**
  486. * @interface Event
  487. * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents
  488. */
  489. var CompositionEventInterface = assign({}, EventInterface, {
  490. data: 0
  491. });
  492. var SyntheticCompositionEvent = createSyntheticEvent(CompositionEventInterface);
  493. /**
  494. * Normalization of deprecated HTML5 `key` values
  495. * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
  496. */
  497. var normalizeKey = {
  498. Esc: 'Escape',
  499. Spacebar: ' ',
  500. Left: 'ArrowLeft',
  501. Up: 'ArrowUp',
  502. Right: 'ArrowRight',
  503. Down: 'ArrowDown',
  504. Del: 'Delete',
  505. Win: 'OS',
  506. Menu: 'ContextMenu',
  507. Apps: 'ContextMenu',
  508. Scroll: 'ScrollLock',
  509. MozPrintableKey: 'Unidentified'
  510. };
  511. /**
  512. * Translation from legacy `keyCode` to HTML5 `key`
  513. * Only special keys supported, all others depend on keyboard layout or browser
  514. * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names
  515. */
  516. var translateToKey = {
  517. '8': 'Backspace',
  518. '9': 'Tab',
  519. '12': 'Clear',
  520. '13': 'Enter',
  521. '16': 'Shift',
  522. '17': 'Control',
  523. '18': 'Alt',
  524. '19': 'Pause',
  525. '20': 'CapsLock',
  526. '27': 'Escape',
  527. '32': ' ',
  528. '33': 'PageUp',
  529. '34': 'PageDown',
  530. '35': 'End',
  531. '36': 'Home',
  532. '37': 'ArrowLeft',
  533. '38': 'ArrowUp',
  534. '39': 'ArrowRight',
  535. '40': 'ArrowDown',
  536. '45': 'Insert',
  537. '46': 'Delete',
  538. '112': 'F1',
  539. '113': 'F2',
  540. '114': 'F3',
  541. '115': 'F4',
  542. '116': 'F5',
  543. '117': 'F6',
  544. '118': 'F7',
  545. '119': 'F8',
  546. '120': 'F9',
  547. '121': 'F10',
  548. '122': 'F11',
  549. '123': 'F12',
  550. '144': 'NumLock',
  551. '145': 'ScrollLock',
  552. '224': 'Meta'
  553. };
  554. /**
  555. * @param {object} nativeEvent Native browser event.
  556. * @return {string} Normalized `key` property.
  557. */
  558. function getEventKey(nativeEvent) {
  559. if (nativeEvent.key) {
  560. // Normalize inconsistent values reported by browsers due to
  561. // implementations of a working draft specification.
  562. // FireFox implements `key` but returns `MozPrintableKey` for all
  563. // printable characters (normalized to `Unidentified`), ignore it.
  564. var key = normalizeKey[nativeEvent.key] || nativeEvent.key;
  565. if (key !== 'Unidentified') {
  566. return key;
  567. }
  568. } // Browser does not implement `key`, polyfill as much of it as we can.
  569. if (nativeEvent.type === 'keypress') {
  570. var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can
  571. // thus be captured by `keypress`, no other non-printable key should.
  572. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode);
  573. }
  574. if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') {
  575. // While user keyboard layout determines the actual meaning of each
  576. // `keyCode` value, almost all function keys have a universal value.
  577. return translateToKey[nativeEvent.keyCode] || 'Unidentified';
  578. }
  579. return '';
  580. }
  581. /**
  582. * Translation from modifier key to the associated property in the event.
  583. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers
  584. */
  585. var modifierKeyToProp = {
  586. Alt: 'altKey',
  587. Control: 'ctrlKey',
  588. Meta: 'metaKey',
  589. Shift: 'shiftKey'
  590. }; // Older browsers (Safari <= 10, iOS Safari <= 10.2) do not support
  591. // getModifierState. If getModifierState is not supported, we map it to a set of
  592. // modifier keys exposed by the event. In this case, Lock-keys are not supported.
  593. function modifierStateGetter(keyArg) {
  594. var syntheticEvent = this;
  595. var nativeEvent = syntheticEvent.nativeEvent;
  596. if (nativeEvent.getModifierState) {
  597. return nativeEvent.getModifierState(keyArg);
  598. }
  599. var keyProp = modifierKeyToProp[keyArg];
  600. return keyProp ? !!nativeEvent[keyProp] : false;
  601. }
  602. function getEventModifierState(nativeEvent) {
  603. return modifierStateGetter;
  604. }
  605. /**
  606. * @interface KeyboardEvent
  607. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  608. */
  609. var KeyboardEventInterface = assign({}, UIEventInterface, {
  610. key: getEventKey,
  611. code: 0,
  612. location: 0,
  613. ctrlKey: 0,
  614. shiftKey: 0,
  615. altKey: 0,
  616. metaKey: 0,
  617. repeat: 0,
  618. locale: 0,
  619. getModifierState: getEventModifierState,
  620. // Legacy Interface
  621. charCode: function (event) {
  622. // `charCode` is the result of a KeyPress event and represents the value of
  623. // the actual printable character.
  624. // KeyPress is deprecated, but its replacement is not yet final and not
  625. // implemented in any major browser. Only KeyPress has charCode.
  626. if (event.type === 'keypress') {
  627. return getEventCharCode(event);
  628. }
  629. return 0;
  630. },
  631. keyCode: function (event) {
  632. // `keyCode` is the result of a KeyDown/Up event and represents the value of
  633. // physical keyboard key.
  634. // The actual meaning of the value depends on the users' keyboard layout
  635. // which cannot be detected. Assuming that it is a US keyboard layout
  636. // provides a surprisingly accurate mapping for US and European users.
  637. // Due to this, it is left to the user to implement at this time.
  638. if (event.type === 'keydown' || event.type === 'keyup') {
  639. return event.keyCode;
  640. }
  641. return 0;
  642. },
  643. which: function (event) {
  644. // `which` is an alias for either `keyCode` or `charCode` depending on the
  645. // type of the event.
  646. if (event.type === 'keypress') {
  647. return getEventCharCode(event);
  648. }
  649. if (event.type === 'keydown' || event.type === 'keyup') {
  650. return event.keyCode;
  651. }
  652. return 0;
  653. }
  654. });
  655. var SyntheticKeyboardEvent = createSyntheticEvent(KeyboardEventInterface);
  656. /**
  657. * @interface PointerEvent
  658. * @see http://www.w3.org/TR/pointerevents/
  659. */
  660. var PointerEventInterface = assign({}, MouseEventInterface, {
  661. pointerId: 0,
  662. width: 0,
  663. height: 0,
  664. pressure: 0,
  665. tangentialPressure: 0,
  666. tiltX: 0,
  667. tiltY: 0,
  668. twist: 0,
  669. pointerType: 0,
  670. isPrimary: 0
  671. });
  672. var SyntheticPointerEvent = createSyntheticEvent(PointerEventInterface);
  673. /**
  674. * @interface TouchEvent
  675. * @see http://www.w3.org/TR/touch-events/
  676. */
  677. var TouchEventInterface = assign({}, UIEventInterface, {
  678. touches: 0,
  679. targetTouches: 0,
  680. changedTouches: 0,
  681. altKey: 0,
  682. metaKey: 0,
  683. ctrlKey: 0,
  684. shiftKey: 0,
  685. getModifierState: getEventModifierState
  686. });
  687. var SyntheticTouchEvent = createSyntheticEvent(TouchEventInterface);
  688. /**
  689. * @interface Event
  690. * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events-
  691. * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent
  692. */
  693. var TransitionEventInterface = assign({}, EventInterface, {
  694. propertyName: 0,
  695. elapsedTime: 0,
  696. pseudoElement: 0
  697. });
  698. var SyntheticTransitionEvent = createSyntheticEvent(TransitionEventInterface);
  699. /**
  700. * @interface WheelEvent
  701. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  702. */
  703. var WheelEventInterface = assign({}, MouseEventInterface, {
  704. deltaX: function (event) {
  705. return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive).
  706. 'wheelDeltaX' in event ? -event.wheelDeltaX : 0;
  707. },
  708. deltaY: function (event) {
  709. return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive).
  710. 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive).
  711. 'wheelDelta' in event ? -event.wheelDelta : 0;
  712. },
  713. deltaZ: 0,
  714. // Browsers without "deltaMode" is reporting in raw wheel delta where one
  715. // notch on the scroll is always +/- 120, roughly equivalent to pixels.
  716. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or
  717. // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size.
  718. deltaMode: 0
  719. });
  720. var SyntheticWheelEvent = createSyntheticEvent(WheelEventInterface);
  721. /**
  722. * HTML nodeType values that represent the type of the node
  723. */
  724. var ELEMENT_NODE = 1;
  725. function invokeGuardedCallbackProd(name, func, context, a, b, c, d, e, f) {
  726. var funcArgs = Array.prototype.slice.call(arguments, 3);
  727. try {
  728. func.apply(context, funcArgs);
  729. } catch (error) {
  730. this.onError(error);
  731. }
  732. }
  733. var invokeGuardedCallbackImpl = invokeGuardedCallbackProd;
  734. {
  735. // In DEV mode, we swap out invokeGuardedCallback for a special version
  736. // that plays more nicely with the browser's DevTools. The idea is to preserve
  737. // "Pause on exceptions" behavior. Because React wraps all user-provided
  738. // functions in invokeGuardedCallback, and the production version of
  739. // invokeGuardedCallback uses a try-catch, all user exceptions are treated
  740. // like caught exceptions, and the DevTools won't pause unless the developer
  741. // takes the extra step of enabling pause on caught exceptions. This is
  742. // unintuitive, though, because even though React has caught the error, from
  743. // the developer's perspective, the error is uncaught.
  744. //
  745. // To preserve the expected "Pause on exceptions" behavior, we don't use a
  746. // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake
  747. // DOM node, and call the user-provided callback from inside an event handler
  748. // for that fake event. If the callback throws, the error is "captured" using
  749. // a global event handler. But because the error happens in a different
  750. // event loop context, it does not interrupt the normal program flow.
  751. // Effectively, this gives us try-catch behavior without actually using
  752. // try-catch. Neat!
  753. // Check that the browser supports the APIs we need to implement our special
  754. // DEV version of invokeGuardedCallback
  755. if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') {
  756. var fakeNode = document.createElement('react');
  757. invokeGuardedCallbackImpl = function invokeGuardedCallbackDev(name, func, context, a, b, c, d, e, f) {
  758. // If document doesn't exist we know for sure we will crash in this method
  759. // when we call document.createEvent(). However this can cause confusing
  760. // errors: https://github.com/facebook/create-react-app/issues/3482
  761. // So we preemptively throw with a better message instead.
  762. if (typeof document === 'undefined' || document === null) {
  763. throw new Error('The `document` global was defined when React was initialized, but is not ' + 'defined anymore. This can happen in a test environment if a component ' + 'schedules an update from an asynchronous callback, but the test has already ' + 'finished running. To solve this, you can either unmount the component at ' + 'the end of your test (and ensure that any asynchronous operations get ' + 'canceled in `componentWillUnmount`), or you can change the test itself ' + 'to be asynchronous.');
  764. }
  765. var evt = document.createEvent('Event');
  766. var didCall = false; // Keeps track of whether the user-provided callback threw an error. We
  767. // set this to true at the beginning, then set it to false right after
  768. // calling the function. If the function errors, `didError` will never be
  769. // set to false. This strategy works even if the browser is flaky and
  770. // fails to call our global error handler, because it doesn't rely on
  771. // the error event at all.
  772. var didError = true; // Keeps track of the value of window.event so that we can reset it
  773. // during the callback to let user code access window.event in the
  774. // browsers that support it.
  775. var windowEvent = window.event; // Keeps track of the descriptor of window.event to restore it after event
  776. // dispatching: https://github.com/facebook/react/issues/13688
  777. var windowEventDescriptor = Object.getOwnPropertyDescriptor(window, 'event');
  778. function restoreAfterDispatch() {
  779. // We immediately remove the callback from event listeners so that
  780. // nested `invokeGuardedCallback` calls do not clash. Otherwise, a
  781. // nested call would trigger the fake event handlers of any call higher
  782. // in the stack.
  783. fakeNode.removeEventListener(evtType, callCallback, false); // We check for window.hasOwnProperty('event') to prevent the
  784. // window.event assignment in both IE <= 10 as they throw an error
  785. // "Member not found" in strict mode, and in Firefox which does not
  786. // support window.event.
  787. if (typeof window.event !== 'undefined' && window.hasOwnProperty('event')) {
  788. window.event = windowEvent;
  789. }
  790. } // Create an event handler for our fake event. We will synchronously
  791. // dispatch our fake event using `dispatchEvent`. Inside the handler, we
  792. // call the user-provided callback.
  793. var funcArgs = Array.prototype.slice.call(arguments, 3);
  794. function callCallback() {
  795. didCall = true;
  796. restoreAfterDispatch();
  797. func.apply(context, funcArgs);
  798. didError = false;
  799. } // Create a global error event handler. We use this to capture the value
  800. // that was thrown. It's possible that this error handler will fire more
  801. // than once; for example, if non-React code also calls `dispatchEvent`
  802. // and a handler for that event throws. We should be resilient to most of
  803. // those cases. Even if our error event handler fires more than once, the
  804. // last error event is always used. If the callback actually does error,
  805. // we know that the last error event is the correct one, because it's not
  806. // possible for anything else to have happened in between our callback
  807. // erroring and the code that follows the `dispatchEvent` call below. If
  808. // the callback doesn't error, but the error event was fired, we know to
  809. // ignore it because `didError` will be false, as described above.
  810. var error; // Use this to track whether the error event is ever called.
  811. var didSetError = false;
  812. var isCrossOriginError = false;
  813. function handleWindowError(event) {
  814. error = event.error;
  815. didSetError = true;
  816. if (error === null && event.colno === 0 && event.lineno === 0) {
  817. isCrossOriginError = true;
  818. }
  819. if (event.defaultPrevented) {
  820. // Some other error handler has prevented default.
  821. // Browsers silence the error report if this happens.
  822. // We'll remember this to later decide whether to log it or not.
  823. if (error != null && typeof error === 'object') {
  824. try {
  825. error._suppressLogging = true;
  826. } catch (inner) {// Ignore.
  827. }
  828. }
  829. }
  830. } // Create a fake event type.
  831. var evtType = "react-" + (name ? name : 'invokeguardedcallback'); // Attach our event handlers
  832. window.addEventListener('error', handleWindowError);
  833. fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function
  834. // errors, it will trigger our global error handler.
  835. evt.initEvent(evtType, false, false);
  836. fakeNode.dispatchEvent(evt);
  837. if (windowEventDescriptor) {
  838. Object.defineProperty(window, 'event', windowEventDescriptor);
  839. }
  840. if (didCall && didError) {
  841. if (!didSetError) {
  842. // The callback errored, but the error event never fired.
  843. // eslint-disable-next-line react-internal/prod-error-codes
  844. error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.');
  845. } else if (isCrossOriginError) {
  846. // eslint-disable-next-line react-internal/prod-error-codes
  847. error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://reactjs.org/link/crossorigin-error for more information.');
  848. }
  849. this.onError(error);
  850. } // Remove our event listeners
  851. window.removeEventListener('error', handleWindowError);
  852. if (!didCall) {
  853. // Something went really wrong, and our event was not dispatched.
  854. // https://github.com/facebook/react/issues/16734
  855. // https://github.com/facebook/react/issues/16585
  856. // Fall back to the production implementation.
  857. restoreAfterDispatch();
  858. return invokeGuardedCallbackProd.apply(this, arguments);
  859. }
  860. };
  861. }
  862. }
  863. var invokeGuardedCallbackImpl$1 = invokeGuardedCallbackImpl;
  864. var hasError = false;
  865. var caughtError = null; // Used by event system to capture/rethrow the first error.
  866. var hasRethrowError = false;
  867. var rethrowError = null;
  868. var reporter = {
  869. onError: function (error) {
  870. hasError = true;
  871. caughtError = error;
  872. }
  873. };
  874. /**
  875. * Call a function while guarding against errors that happens within it.
  876. * Returns an error if it throws, otherwise null.
  877. *
  878. * In production, this is implemented using a try-catch. The reason we don't
  879. * use a try-catch directly is so that we can swap out a different
  880. * implementation in DEV mode.
  881. *
  882. * @param {String} name of the guard to use for logging or debugging
  883. * @param {Function} func The function to invoke
  884. * @param {*} context The context to use when calling the function
  885. * @param {...*} args Arguments for function
  886. */
  887. function invokeGuardedCallback(name, func, context, a, b, c, d, e, f) {
  888. hasError = false;
  889. caughtError = null;
  890. invokeGuardedCallbackImpl$1.apply(reporter, arguments);
  891. }
  892. /**
  893. * Same as invokeGuardedCallback, but instead of returning an error, it stores
  894. * it in a global so it can be rethrown by `rethrowCaughtError` later.
  895. * TODO: See if caughtError and rethrowError can be unified.
  896. *
  897. * @param {String} name of the guard to use for logging or debugging
  898. * @param {Function} func The function to invoke
  899. * @param {*} context The context to use when calling the function
  900. * @param {...*} args Arguments for function
  901. */
  902. function invokeGuardedCallbackAndCatchFirstError(name, func, context, a, b, c, d, e, f) {
  903. invokeGuardedCallback.apply(this, arguments);
  904. if (hasError) {
  905. var error = clearCaughtError();
  906. if (!hasRethrowError) {
  907. hasRethrowError = true;
  908. rethrowError = error;
  909. }
  910. }
  911. }
  912. /**
  913. * During execution of guarded functions we will capture the first error which
  914. * we will rethrow to be handled by the top level error handler.
  915. */
  916. function rethrowCaughtError() {
  917. if (hasRethrowError) {
  918. var error = rethrowError;
  919. hasRethrowError = false;
  920. rethrowError = null;
  921. throw error;
  922. }
  923. }
  924. function clearCaughtError() {
  925. if (hasError) {
  926. var error = caughtError;
  927. hasError = false;
  928. caughtError = null;
  929. return error;
  930. } else {
  931. throw new Error('clearCaughtError was called but no error was captured. This error ' + 'is likely caused by a bug in React. Please file an issue.');
  932. }
  933. }
  934. var isArrayImpl = Array.isArray; // eslint-disable-next-line no-redeclare
  935. function isArray(a) {
  936. return isArrayImpl(a);
  937. }
  938. var SecretInternals = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
  939. var EventInternals = SecretInternals.Events;
  940. var getInstanceFromNode = EventInternals[0];
  941. var getNodeFromInstance = EventInternals[1];
  942. var getFiberCurrentPropsFromNode = EventInternals[2];
  943. var enqueueStateRestore = EventInternals[3];
  944. var restoreStateIfNeeded = EventInternals[4];
  945. var act = React.unstable_act;
  946. function Event(suffix) {}
  947. var hasWarnedAboutDeprecatedMockComponent = false;
  948. /**
  949. * @class ReactTestUtils
  950. */
  951. function findAllInRenderedFiberTreeInternal(fiber, test) {
  952. if (!fiber) {
  953. return [];
  954. }
  955. var currentParent = findCurrentFiberUsingSlowPath(fiber);
  956. if (!currentParent) {
  957. return [];
  958. }
  959. var node = currentParent;
  960. var ret = [];
  961. while (true) {
  962. if (node.tag === HostComponent || node.tag === HostText || node.tag === ClassComponent || node.tag === FunctionComponent) {
  963. var publicInst = node.stateNode;
  964. if (test(publicInst)) {
  965. ret.push(publicInst);
  966. }
  967. }
  968. if (node.child) {
  969. node.child.return = node;
  970. node = node.child;
  971. continue;
  972. }
  973. if (node === currentParent) {
  974. return ret;
  975. }
  976. while (!node.sibling) {
  977. if (!node.return || node.return === currentParent) {
  978. return ret;
  979. }
  980. node = node.return;
  981. }
  982. node.sibling.return = node.return;
  983. node = node.sibling;
  984. }
  985. }
  986. function validateClassInstance(inst, methodName) {
  987. if (!inst) {
  988. // This is probably too relaxed but it's existing behavior.
  989. return;
  990. }
  991. if (get(inst)) {
  992. // This is a public instance indeed.
  993. return;
  994. }
  995. var received;
  996. var stringified = String(inst);
  997. if (isArray(inst)) {
  998. received = 'an array';
  999. } else if (inst && inst.nodeType === ELEMENT_NODE && inst.tagName) {
  1000. received = 'a DOM node';
  1001. } else if (stringified === '[object Object]') {
  1002. received = 'object with keys {' + Object.keys(inst).join(', ') + '}';
  1003. } else {
  1004. received = stringified;
  1005. }
  1006. throw new Error(methodName + "(...): the first argument must be a React class instance. " + ("Instead received: " + received + "."));
  1007. }
  1008. /**
  1009. * Utilities for making it easy to test React components.
  1010. *
  1011. * See https://reactjs.org/docs/test-utils.html
  1012. *
  1013. * Todo: Support the entire DOM.scry query syntax. For now, these simple
  1014. * utilities will suffice for testing purposes.
  1015. * @lends ReactTestUtils
  1016. */
  1017. function renderIntoDocument(element) {
  1018. var div = document.createElement('div'); // None of our tests actually require attaching the container to the
  1019. // DOM, and doing so creates a mess that we rely on test isolation to
  1020. // clean up, so we're going to stop honoring the name of this method
  1021. // (and probably rename it eventually) if no problems arise.
  1022. // document.documentElement.appendChild(div);
  1023. return ReactDOM.render(element, div);
  1024. }
  1025. function isElement(element) {
  1026. return React.isValidElement(element);
  1027. }
  1028. function isElementOfType(inst, convenienceConstructor) {
  1029. return React.isValidElement(inst) && inst.type === convenienceConstructor;
  1030. }
  1031. function isDOMComponent(inst) {
  1032. return !!(inst && inst.nodeType === ELEMENT_NODE && inst.tagName);
  1033. }
  1034. function isDOMComponentElement(inst) {
  1035. return !!(inst && React.isValidElement(inst) && !!inst.tagName);
  1036. }
  1037. function isCompositeComponent(inst) {
  1038. if (isDOMComponent(inst)) {
  1039. // Accessing inst.setState warns; just return false as that'll be what
  1040. // this returns when we have DOM nodes as refs directly
  1041. return false;
  1042. }
  1043. return inst != null && typeof inst.render === 'function' && typeof inst.setState === 'function';
  1044. }
  1045. function isCompositeComponentWithType(inst, type) {
  1046. if (!isCompositeComponent(inst)) {
  1047. return false;
  1048. }
  1049. var internalInstance = get(inst);
  1050. var constructor = internalInstance.type;
  1051. return constructor === type;
  1052. }
  1053. function findAllInRenderedTree(inst, test) {
  1054. validateClassInstance(inst, 'findAllInRenderedTree');
  1055. if (!inst) {
  1056. return [];
  1057. }
  1058. var internalInstance = get(inst);
  1059. return findAllInRenderedFiberTreeInternal(internalInstance, test);
  1060. }
  1061. /**
  1062. * Finds all instances of components in the rendered tree that are DOM
  1063. * components with the class name matching `className`.
  1064. * @return {array} an array of all the matches.
  1065. */
  1066. function scryRenderedDOMComponentsWithClass(root, classNames) {
  1067. validateClassInstance(root, 'scryRenderedDOMComponentsWithClass');
  1068. return findAllInRenderedTree(root, function (inst) {
  1069. if (isDOMComponent(inst)) {
  1070. var className = inst.className;
  1071. if (typeof className !== 'string') {
  1072. // SVG, probably.
  1073. className = inst.getAttribute('class') || '';
  1074. }
  1075. var classList = className.split(/\s+/);
  1076. if (!isArray(classNames)) {
  1077. if (classNames === undefined) {
  1078. throw new Error('TestUtils.scryRenderedDOMComponentsWithClass expects a ' + 'className as a second argument.');
  1079. }
  1080. classNames = classNames.split(/\s+/);
  1081. }
  1082. return classNames.every(function (name) {
  1083. return classList.indexOf(name) !== -1;
  1084. });
  1085. }
  1086. return false;
  1087. });
  1088. }
  1089. /**
  1090. * Like scryRenderedDOMComponentsWithClass but expects there to be one result,
  1091. * and returns that one result, or throws exception if there is any other
  1092. * number of matches besides one.
  1093. * @return {!ReactDOMComponent} The one match.
  1094. */
  1095. function findRenderedDOMComponentWithClass(root, className) {
  1096. validateClassInstance(root, 'findRenderedDOMComponentWithClass');
  1097. var all = scryRenderedDOMComponentsWithClass(root, className);
  1098. if (all.length !== 1) {
  1099. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for class:' + className);
  1100. }
  1101. return all[0];
  1102. }
  1103. /**
  1104. * Finds all instances of components in the rendered tree that are DOM
  1105. * components with the tag name matching `tagName`.
  1106. * @return {array} an array of all the matches.
  1107. */
  1108. function scryRenderedDOMComponentsWithTag(root, tagName) {
  1109. validateClassInstance(root, 'scryRenderedDOMComponentsWithTag');
  1110. return findAllInRenderedTree(root, function (inst) {
  1111. return isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase();
  1112. });
  1113. }
  1114. /**
  1115. * Like scryRenderedDOMComponentsWithTag but expects there to be one result,
  1116. * and returns that one result, or throws exception if there is any other
  1117. * number of matches besides one.
  1118. * @return {!ReactDOMComponent} The one match.
  1119. */
  1120. function findRenderedDOMComponentWithTag(root, tagName) {
  1121. validateClassInstance(root, 'findRenderedDOMComponentWithTag');
  1122. var all = scryRenderedDOMComponentsWithTag(root, tagName);
  1123. if (all.length !== 1) {
  1124. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for tag:' + tagName);
  1125. }
  1126. return all[0];
  1127. }
  1128. /**
  1129. * Finds all instances of components with type equal to `componentType`.
  1130. * @return {array} an array of all the matches.
  1131. */
  1132. function scryRenderedComponentsWithType(root, componentType) {
  1133. validateClassInstance(root, 'scryRenderedComponentsWithType');
  1134. return findAllInRenderedTree(root, function (inst) {
  1135. return isCompositeComponentWithType(inst, componentType);
  1136. });
  1137. }
  1138. /**
  1139. * Same as `scryRenderedComponentsWithType` but expects there to be one result
  1140. * and returns that one result, or throws exception if there is any other
  1141. * number of matches besides one.
  1142. * @return {!ReactComponent} The one match.
  1143. */
  1144. function findRenderedComponentWithType(root, componentType) {
  1145. validateClassInstance(root, 'findRenderedComponentWithType');
  1146. var all = scryRenderedComponentsWithType(root, componentType);
  1147. if (all.length !== 1) {
  1148. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for componentType:' + componentType);
  1149. }
  1150. return all[0];
  1151. }
  1152. /**
  1153. * Pass a mocked component module to this method to augment it with
  1154. * useful methods that allow it to be used as a dummy React component.
  1155. * Instead of rendering as usual, the component will become a simple
  1156. * <div> containing any provided children.
  1157. *
  1158. * @param {object} module the mock function object exported from a
  1159. * module that defines the component to be mocked
  1160. * @param {?string} mockTagName optional dummy root tag name to return
  1161. * from render method (overrides
  1162. * module.mockTagName if provided)
  1163. * @return {object} the ReactTestUtils object (for chaining)
  1164. */
  1165. function mockComponent(module, mockTagName) {
  1166. {
  1167. if (!hasWarnedAboutDeprecatedMockComponent) {
  1168. hasWarnedAboutDeprecatedMockComponent = true;
  1169. warn('ReactTestUtils.mockComponent() is deprecated. ' + 'Use shallow rendering or jest.mock() instead.\n\n' + 'See https://reactjs.org/link/test-utils-mock-component for more information.');
  1170. }
  1171. }
  1172. mockTagName = mockTagName || module.mockTagName || 'div';
  1173. module.prototype.render.mockImplementation(function () {
  1174. return React.createElement(mockTagName, null, this.props.children);
  1175. });
  1176. return this;
  1177. }
  1178. function nativeTouchData(x, y) {
  1179. return {
  1180. touches: [{
  1181. pageX: x,
  1182. pageY: y
  1183. }]
  1184. };
  1185. } // Start of inline: the below functions were inlined from
  1186. // EventPropagator.js, as they deviated from ReactDOM's newer
  1187. // implementations.
  1188. /**
  1189. * Dispatch the event to the listener.
  1190. * @param {SyntheticEvent} event SyntheticEvent to handle
  1191. * @param {function} listener Application-level callback
  1192. * @param {*} inst Internal component instance
  1193. */
  1194. function executeDispatch(event, listener, inst) {
  1195. var type = event.type || 'unknown-event';
  1196. event.currentTarget = getNodeFromInstance(inst);
  1197. invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event);
  1198. event.currentTarget = null;
  1199. }
  1200. /**
  1201. * Standard/simple iteration through an event's collected dispatches.
  1202. */
  1203. function executeDispatchesInOrder(event) {
  1204. var dispatchListeners = event._dispatchListeners;
  1205. var dispatchInstances = event._dispatchInstances;
  1206. if (isArray(dispatchListeners)) {
  1207. for (var i = 0; i < dispatchListeners.length; i++) {
  1208. if (event.isPropagationStopped()) {
  1209. break;
  1210. } // Listeners and Instances are two parallel arrays that are always in sync.
  1211. executeDispatch(event, dispatchListeners[i], dispatchInstances[i]);
  1212. }
  1213. } else if (dispatchListeners) {
  1214. executeDispatch(event, dispatchListeners, dispatchInstances);
  1215. }
  1216. event._dispatchListeners = null;
  1217. event._dispatchInstances = null;
  1218. }
  1219. /**
  1220. * Dispatches an event and releases it back into the pool, unless persistent.
  1221. *
  1222. * @param {?object} event Synthetic event to be dispatched.
  1223. * @private
  1224. */
  1225. var executeDispatchesAndRelease = function (event) {
  1226. if (event) {
  1227. executeDispatchesInOrder(event);
  1228. if (!event.isPersistent()) {
  1229. event.constructor.release(event);
  1230. }
  1231. }
  1232. };
  1233. function isInteractive(tag) {
  1234. return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea';
  1235. }
  1236. function getParent(inst) {
  1237. do {
  1238. inst = inst.return; // TODO: If this is a HostRoot we might want to bail out.
  1239. // That is depending on if we want nested subtrees (layers) to bubble
  1240. // events to their parent. We could also go through parentNode on the
  1241. // host node but that wouldn't work for React Native and doesn't let us
  1242. // do the portal feature.
  1243. } while (inst && inst.tag !== HostComponent);
  1244. if (inst) {
  1245. return inst;
  1246. }
  1247. return null;
  1248. }
  1249. /**
  1250. * Simulates the traversal of a two-phase, capture/bubble event dispatch.
  1251. */
  1252. function traverseTwoPhase(inst, fn, arg) {
  1253. var path = [];
  1254. while (inst) {
  1255. path.push(inst);
  1256. inst = getParent(inst);
  1257. }
  1258. var i;
  1259. for (i = path.length; i-- > 0;) {
  1260. fn(path[i], 'captured', arg);
  1261. }
  1262. for (i = 0; i < path.length; i++) {
  1263. fn(path[i], 'bubbled', arg);
  1264. }
  1265. }
  1266. function shouldPreventMouseEvent(name, type, props) {
  1267. switch (name) {
  1268. case 'onClick':
  1269. case 'onClickCapture':
  1270. case 'onDoubleClick':
  1271. case 'onDoubleClickCapture':
  1272. case 'onMouseDown':
  1273. case 'onMouseDownCapture':
  1274. case 'onMouseMove':
  1275. case 'onMouseMoveCapture':
  1276. case 'onMouseUp':
  1277. case 'onMouseUpCapture':
  1278. case 'onMouseEnter':
  1279. return !!(props.disabled && isInteractive(type));
  1280. default:
  1281. return false;
  1282. }
  1283. }
  1284. /**
  1285. * @param {object} inst The instance, which is the source of events.
  1286. * @param {string} registrationName Name of listener (e.g. `onClick`).
  1287. * @return {?function} The stored callback.
  1288. */
  1289. function getListener(inst, registrationName) {
  1290. // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not
  1291. // live here; needs to be moved to a better place soon
  1292. var stateNode = inst.stateNode;
  1293. if (!stateNode) {
  1294. // Work in progress (ex: onload events in incremental mode).
  1295. return null;
  1296. }
  1297. var props = getFiberCurrentPropsFromNode(stateNode);
  1298. if (!props) {
  1299. // Work in progress.
  1300. return null;
  1301. }
  1302. var listener = props[registrationName];
  1303. if (shouldPreventMouseEvent(registrationName, inst.type, props)) {
  1304. return null;
  1305. }
  1306. if (listener && typeof listener !== 'function') {
  1307. throw new Error("Expected `" + registrationName + "` listener to be a function, instead got a value of `" + typeof listener + "` type.");
  1308. }
  1309. return listener;
  1310. }
  1311. function listenerAtPhase(inst, event, propagationPhase) {
  1312. var registrationName = event._reactName;
  1313. if (propagationPhase === 'captured') {
  1314. registrationName += 'Capture';
  1315. }
  1316. return getListener(inst, registrationName);
  1317. }
  1318. function accumulateDispatches(inst, ignoredDirection, event) {
  1319. if (inst && event && event._reactName) {
  1320. var registrationName = event._reactName;
  1321. var listener = getListener(inst, registrationName);
  1322. if (listener) {
  1323. if (event._dispatchListeners == null) {
  1324. event._dispatchListeners = [];
  1325. }
  1326. if (event._dispatchInstances == null) {
  1327. event._dispatchInstances = [];
  1328. }
  1329. event._dispatchListeners.push(listener);
  1330. event._dispatchInstances.push(inst);
  1331. }
  1332. }
  1333. }
  1334. function accumulateDirectionalDispatches(inst, phase, event) {
  1335. {
  1336. if (!inst) {
  1337. error('Dispatching inst must not be null');
  1338. }
  1339. }
  1340. var listener = listenerAtPhase(inst, event, phase);
  1341. if (listener) {
  1342. if (event._dispatchListeners == null) {
  1343. event._dispatchListeners = [];
  1344. }
  1345. if (event._dispatchInstances == null) {
  1346. event._dispatchInstances = [];
  1347. }
  1348. event._dispatchListeners.push(listener);
  1349. event._dispatchInstances.push(inst);
  1350. }
  1351. }
  1352. function accumulateDirectDispatchesSingle(event) {
  1353. if (event && event._reactName) {
  1354. accumulateDispatches(event._targetInst, null, event);
  1355. }
  1356. }
  1357. function accumulateTwoPhaseDispatchesSingle(event) {
  1358. if (event && event._reactName) {
  1359. traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event);
  1360. }
  1361. } // End of inline
  1362. var Simulate = {};
  1363. var directDispatchEventTypes = new Set(['mouseEnter', 'mouseLeave', 'pointerEnter', 'pointerLeave']);
  1364. /**
  1365. * Exports:
  1366. *
  1367. * - `Simulate.click(Element)`
  1368. * - `Simulate.mouseMove(Element)`
  1369. * - `Simulate.change(Element)`
  1370. * - ... (All keys from event plugin `eventTypes` objects)
  1371. */
  1372. function makeSimulator(eventType) {
  1373. return function (domNode, eventData) {
  1374. if (React.isValidElement(domNode)) {
  1375. throw new Error('TestUtils.Simulate expected a DOM node as the first argument but received ' + 'a React element. Pass the DOM node you wish to simulate the event on instead. ' + 'Note that TestUtils.Simulate will not work if you are using shallow rendering.');
  1376. }
  1377. if (isCompositeComponent(domNode)) {
  1378. throw new Error('TestUtils.Simulate expected a DOM node as the first argument but received ' + 'a component instance. Pass the DOM node you wish to simulate the event on instead.');
  1379. }
  1380. var reactName = 'on' + eventType[0].toUpperCase() + eventType.slice(1);
  1381. var fakeNativeEvent = new Event();
  1382. fakeNativeEvent.target = domNode;
  1383. fakeNativeEvent.type = eventType.toLowerCase();
  1384. var targetInst = getInstanceFromNode(domNode);
  1385. var event = new SyntheticEvent(reactName, fakeNativeEvent.type, targetInst, fakeNativeEvent, domNode); // Since we aren't using pooling, always persist the event. This will make
  1386. // sure it's marked and won't warn when setting additional properties.
  1387. event.persist();
  1388. assign(event, eventData);
  1389. if (directDispatchEventTypes.has(eventType)) {
  1390. accumulateDirectDispatchesSingle(event);
  1391. } else {
  1392. accumulateTwoPhaseDispatchesSingle(event);
  1393. }
  1394. ReactDOM.unstable_batchedUpdates(function () {
  1395. // Normally extractEvent enqueues a state restore, but we'll just always
  1396. // do that since we're by-passing it here.
  1397. enqueueStateRestore(domNode);
  1398. executeDispatchesAndRelease(event);
  1399. rethrowCaughtError();
  1400. });
  1401. restoreStateIfNeeded();
  1402. };
  1403. } // A one-time snapshot with no plans to update. We'll probably want to deprecate Simulate API.
  1404. var simulatedEventTypes = ['blur', 'cancel', 'click', 'close', 'contextMenu', 'copy', 'cut', 'auxClick', 'doubleClick', 'dragEnd', 'dragStart', 'drop', 'focus', 'input', 'invalid', 'keyDown', 'keyPress', 'keyUp', 'mouseDown', 'mouseUp', 'paste', 'pause', 'play', 'pointerCancel', 'pointerDown', 'pointerUp', 'rateChange', 'reset', 'resize', 'seeked', 'submit', 'touchCancel', 'touchEnd', 'touchStart', 'volumeChange', 'drag', 'dragEnter', 'dragExit', 'dragLeave', 'dragOver', 'mouseMove', 'mouseOut', 'mouseOver', 'pointerMove', 'pointerOut', 'pointerOver', 'scroll', 'toggle', 'touchMove', 'wheel', 'abort', 'animationEnd', 'animationIteration', 'animationStart', 'canPlay', 'canPlayThrough', 'durationChange', 'emptied', 'encrypted', 'ended', 'error', 'gotPointerCapture', 'load', 'loadedData', 'loadedMetadata', 'loadStart', 'lostPointerCapture', 'playing', 'progress', 'seeking', 'stalled', 'suspend', 'timeUpdate', 'transitionEnd', 'waiting', 'mouseEnter', 'mouseLeave', 'pointerEnter', 'pointerLeave', 'change', 'select', 'beforeInput', 'compositionEnd', 'compositionStart', 'compositionUpdate'];
  1405. function buildSimulators() {
  1406. simulatedEventTypes.forEach(function (eventType) {
  1407. Simulate[eventType] = makeSimulator(eventType);
  1408. });
  1409. }
  1410. buildSimulators();
  1411. exports.Simulate = Simulate;
  1412. exports.act = act;
  1413. exports.findAllInRenderedTree = findAllInRenderedTree;
  1414. exports.findRenderedComponentWithType = findRenderedComponentWithType;
  1415. exports.findRenderedDOMComponentWithClass = findRenderedDOMComponentWithClass;
  1416. exports.findRenderedDOMComponentWithTag = findRenderedDOMComponentWithTag;
  1417. exports.isCompositeComponent = isCompositeComponent;
  1418. exports.isCompositeComponentWithType = isCompositeComponentWithType;
  1419. exports.isDOMComponent = isDOMComponent;
  1420. exports.isDOMComponentElement = isDOMComponentElement;
  1421. exports.isElement = isElement;
  1422. exports.isElementOfType = isElementOfType;
  1423. exports.mockComponent = mockComponent;
  1424. exports.nativeTouchData = nativeTouchData;
  1425. exports.renderIntoDocument = renderIntoDocument;
  1426. exports.scryRenderedComponentsWithType = scryRenderedComponentsWithType;
  1427. exports.scryRenderedDOMComponentsWithClass = scryRenderedDOMComponentsWithClass;
  1428. exports.scryRenderedDOMComponentsWithTag = scryRenderedDOMComponentsWithTag;
  1429. exports.traverseTwoPhase = traverseTwoPhase;
  1430. })();
  1431. }