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

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