Dashboard sipadu mbip
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637
  1. /** @license React v16.12.0
  2. * react-dom-test-utils.development.js
  3. *
  4. * Copyright (c) Facebook, Inc. and its affiliates.
  5. *
  6. * This source code is licensed under the MIT license found in the
  7. * LICENSE file in the root directory of this source tree.
  8. */
  9. 'use strict';
  10. if (process.env.NODE_ENV !== "production") {
  11. (function() {
  12. 'use strict';
  13. var _assign = require('object-assign');
  14. var React = require('react');
  15. var ReactDOM = require('react-dom');
  16. var Scheduler = require('scheduler');
  17. // Do not require this module directly! Use normal `invariant` calls with
  18. // template literal strings. The messages will be replaced with error codes
  19. // during build.
  20. /**
  21. * Use invariant() to assert state which your program assumes to be true.
  22. *
  23. * Provide sprintf-style format (only %s is supported) and arguments
  24. * to provide information about what broke and what you were
  25. * expecting.
  26. *
  27. * The invariant message will be stripped in production, but the invariant
  28. * will remain to ensure logic does not differ in production.
  29. */
  30. /**
  31. * Similar to invariant but only logs a warning if the condition is not met.
  32. * This can be used to log issues in development environments in critical
  33. * paths. Removing the logging code for production environments will keep the
  34. * same logic and follow the same code paths.
  35. */
  36. var warningWithoutStack = function () {};
  37. {
  38. warningWithoutStack = function (condition, format) {
  39. for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
  40. args[_key - 2] = arguments[_key];
  41. }
  42. if (format === undefined) {
  43. throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
  44. }
  45. if (args.length > 8) {
  46. // Check before the condition to catch violations early.
  47. throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
  48. }
  49. if (condition) {
  50. return;
  51. }
  52. if (typeof console !== 'undefined') {
  53. var argsWithFormat = args.map(function (item) {
  54. return '' + item;
  55. });
  56. argsWithFormat.unshift('Warning: ' + format); // We intentionally don't use spread (or .apply) directly because it
  57. // breaks IE9: https://github.com/facebook/react/issues/13610
  58. Function.prototype.apply.call(console.error, console, argsWithFormat);
  59. }
  60. try {
  61. // --- Welcome to debugging React ---
  62. // This error was thrown as a convenience so that you can use this stack
  63. // to find the callsite that caused this warning to fire.
  64. var argIndex = 0;
  65. var message = 'Warning: ' + format.replace(/%s/g, function () {
  66. return args[argIndex++];
  67. });
  68. throw new Error(message);
  69. } catch (x) {}
  70. };
  71. }
  72. var warningWithoutStack$1 = warningWithoutStack;
  73. /**
  74. * `ReactInstanceMap` maintains a mapping from a public facing stateful
  75. * instance (key) and the internal representation (value). This allows public
  76. * methods to accept the user facing instance as an argument and map them back
  77. * to internal methods.
  78. *
  79. * Note that this module is currently shared and assumed to be stateless.
  80. * If this becomes an actual Map, that will break.
  81. */
  82. /**
  83. * This API should be called `delete` but we'd have to make sure to always
  84. * transform these to strings for IE support. When this transform is fully
  85. * supported we can rename it.
  86. */
  87. function get(key) {
  88. return key._reactInternalFiber;
  89. }
  90. var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer renderers from RTE when used with older react package versions.
  91. // Current owner and dispatcher used to share the same ref,
  92. // but PR #14548 split them out to better support the react-debug-tools package.
  93. if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
  94. ReactSharedInternals.ReactCurrentDispatcher = {
  95. current: null
  96. };
  97. }
  98. if (!ReactSharedInternals.hasOwnProperty('ReactCurrentBatchConfig')) {
  99. ReactSharedInternals.ReactCurrentBatchConfig = {
  100. suspense: null
  101. };
  102. }
  103. // The Symbol used to tag the ReactElement-like types. If there is no native Symbol
  104. // nor polyfill, then a plain number is used for performance.
  105. // TODO: We don't use AsyncMode or ConcurrentMode anymore. They were temporary
  106. // (unstable) APIs that have been removed. Can we remove the symbols?
  107. {
  108. }
  109. var FunctionComponent = 0;
  110. var ClassComponent = 1;
  111. // Before we know whether it is function or class
  112. var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
  113. // A subtree. Could be an entry point to a different renderer.
  114. var HostComponent = 5;
  115. var HostText = 6;
  116. // Don't change these two values. They're used by React Dev Tools.
  117. var NoEffect =
  118. /* */
  119. 0;
  120. // You can change the rest (and add more).
  121. var Placement =
  122. /* */
  123. 2;
  124. var Hydrating =
  125. /* */
  126. 1024;
  127. // Passive & Update & Callback & Ref & Snapshot
  128. // Union of all host effects
  129. // Helps identify side effects in render-phase lifecycle hooks and setState
  130. // reducers by double invoking them in Strict Mode.
  131. // To preserve the "Pause on caught exceptions" behavior of the debugger, we
  132. // replay the begin phase of a failed component inside invokeGuardedCallback.
  133. // Warn about deprecated, async-unsafe lifecycles; relates to RFC #6:
  134. // Gather advanced timing metrics for Profiler subtrees.
  135. // Trace which interactions trigger each commit.
  136. // SSR experiments
  137. // Only used in www builds.
  138. // Only used in www builds.
  139. // Disable javascript: URL strings in href for XSS protection.
  140. // React Fire: prevent the value and checked attributes from syncing
  141. // with their related DOM properties
  142. // These APIs will no longer be "unstable" in the upcoming 16.7 release,
  143. // Control this behavior with a flag to support 16.6 minor releases in the meanwhile.
  144. // Experimental React Flare event system and event components support.
  145. // Experimental Host Component support.
  146. // Experimental Scope support.
  147. // New API for JSX transforms to target - https://github.com/reactjs/rfcs/pull/107
  148. // We will enforce mocking scheduler with scheduler/unstable_mock at some point. (v17?)
  149. // Till then, we warn about the missing mock, but still fallback to a legacy mode compatible version
  150. // For tests, we flush suspense fallbacks in an act scope;
  151. // *except* in some of our own tests, where we test incremental loading states.
  152. // Add a callback property to suspense to notify which promises are currently
  153. // in the update queue. This allows reporting and tracing of what is causing
  154. // the user to see a loading state.
  155. // Also allows hydration callbacks to fire when a dehydrated boundary gets
  156. // hydrated or deleted.
  157. // Part of the simplification of React.createElement so we can eventually move
  158. // from React.createElement to React.jsx
  159. // https://github.com/reactjs/rfcs/blob/createlement-rfc/text/0000-create-element-changes.md
  160. // Flag to turn event.target and event.currentTarget in ReactNative from a reactTag to a component instance
  161. var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner;
  162. function getNearestMountedFiber(fiber) {
  163. var node = fiber;
  164. var nearestMounted = fiber;
  165. if (!fiber.alternate) {
  166. // If there is no alternate, this might be a new tree that isn't inserted
  167. // yet. If it is, then it will have a pending insertion effect on it.
  168. var nextNode = node;
  169. do {
  170. node = nextNode;
  171. if ((node.effectTag & (Placement | Hydrating)) !== NoEffect) {
  172. // This is an insertion or in-progress hydration. The nearest possible
  173. // mounted fiber is the parent but we need to continue to figure out
  174. // if that one is still mounted.
  175. nearestMounted = node.return;
  176. }
  177. nextNode = node.return;
  178. } while (nextNode);
  179. } else {
  180. while (node.return) {
  181. node = node.return;
  182. }
  183. }
  184. if (node.tag === HostRoot) {
  185. // TODO: Check if this was a nested HostRoot when used with
  186. // renderContainerIntoSubtree.
  187. return nearestMounted;
  188. } // If we didn't hit the root, that means that we're in an disconnected tree
  189. // that has been unmounted.
  190. return null;
  191. }
  192. function assertIsMounted(fiber) {
  193. if (!(getNearestMountedFiber(fiber) === fiber)) {
  194. {
  195. throw Error("Unable to find node on an unmounted component.");
  196. }
  197. }
  198. }
  199. function findCurrentFiberUsingSlowPath(fiber) {
  200. var alternate = fiber.alternate;
  201. if (!alternate) {
  202. // If there is no alternate, then we only need to check if it is mounted.
  203. var nearestMounted = getNearestMountedFiber(fiber);
  204. if (!(nearestMounted !== null)) {
  205. {
  206. throw Error("Unable to find node on an unmounted component.");
  207. }
  208. }
  209. if (nearestMounted !== fiber) {
  210. return null;
  211. }
  212. return fiber;
  213. } // If we have two possible branches, we'll walk backwards up to the root
  214. // to see what path the root points to. On the way we may hit one of the
  215. // special cases and we'll deal with them.
  216. var a = fiber;
  217. var b = alternate;
  218. while (true) {
  219. var parentA = a.return;
  220. if (parentA === null) {
  221. // We're at the root.
  222. break;
  223. }
  224. var parentB = parentA.alternate;
  225. if (parentB === null) {
  226. // There is no alternate. This is an unusual case. Currently, it only
  227. // happens when a Suspense component is hidden. An extra fragment fiber
  228. // is inserted in between the Suspense fiber and its children. Skip
  229. // over this extra fragment fiber and proceed to the next parent.
  230. var nextParent = parentA.return;
  231. if (nextParent !== null) {
  232. a = b = nextParent;
  233. continue;
  234. } // If there's no parent, we're at the root.
  235. break;
  236. } // If both copies of the parent fiber point to the same child, we can
  237. // assume that the child is current. This happens when we bailout on low
  238. // priority: the bailed out fiber's child reuses the current child.
  239. if (parentA.child === parentB.child) {
  240. var child = parentA.child;
  241. while (child) {
  242. if (child === a) {
  243. // We've determined that A is the current branch.
  244. assertIsMounted(parentA);
  245. return fiber;
  246. }
  247. if (child === b) {
  248. // We've determined that B is the current branch.
  249. assertIsMounted(parentA);
  250. return alternate;
  251. }
  252. child = child.sibling;
  253. } // We should never have an alternate for any mounting node. So the only
  254. // way this could possibly happen is if this was unmounted, if at all.
  255. {
  256. {
  257. throw Error("Unable to find node on an unmounted component.");
  258. }
  259. }
  260. }
  261. if (a.return !== b.return) {
  262. // The return pointer of A and the return pointer of B point to different
  263. // fibers. We assume that return pointers never criss-cross, so A must
  264. // belong to the child set of A.return, and B must belong to the child
  265. // set of B.return.
  266. a = parentA;
  267. b = parentB;
  268. } else {
  269. // The return pointers point to the same fiber. We'll have to use the
  270. // default, slow path: scan the child sets of each parent alternate to see
  271. // which child belongs to which set.
  272. //
  273. // Search parent A's child set
  274. var didFindChild = false;
  275. var _child = parentA.child;
  276. while (_child) {
  277. if (_child === a) {
  278. didFindChild = true;
  279. a = parentA;
  280. b = parentB;
  281. break;
  282. }
  283. if (_child === b) {
  284. didFindChild = true;
  285. b = parentA;
  286. a = parentB;
  287. break;
  288. }
  289. _child = _child.sibling;
  290. }
  291. if (!didFindChild) {
  292. // Search parent B's child set
  293. _child = parentB.child;
  294. while (_child) {
  295. if (_child === a) {
  296. didFindChild = true;
  297. a = parentB;
  298. b = parentA;
  299. break;
  300. }
  301. if (_child === b) {
  302. didFindChild = true;
  303. b = parentB;
  304. a = parentA;
  305. break;
  306. }
  307. _child = _child.sibling;
  308. }
  309. if (!didFindChild) {
  310. {
  311. throw Error("Child was not found in either parent set. This indicates a bug in React related to the return pointer. Please file an issue.");
  312. }
  313. }
  314. }
  315. }
  316. if (!(a.alternate === b)) {
  317. {
  318. throw Error("Return fibers should always be each others' alternates. This error is likely caused by a bug in React. Please file an issue.");
  319. }
  320. }
  321. } // If the root is not a host container, we're in a disconnected tree. I.e.
  322. // unmounted.
  323. if (!(a.tag === HostRoot)) {
  324. {
  325. throw Error("Unable to find node on an unmounted component.");
  326. }
  327. }
  328. if (a.stateNode.current === a) {
  329. // We've determined that A is the current branch.
  330. return fiber;
  331. } // Otherwise B has to be current branch.
  332. return alternate;
  333. }
  334. /* eslint valid-typeof: 0 */
  335. var EVENT_POOL_SIZE = 10;
  336. /**
  337. * @interface Event
  338. * @see http://www.w3.org/TR/DOM-Level-3-Events/
  339. */
  340. var EventInterface = {
  341. type: null,
  342. target: null,
  343. // currentTarget is set when dispatching; no use in copying it here
  344. currentTarget: function () {
  345. return null;
  346. },
  347. eventPhase: null,
  348. bubbles: null,
  349. cancelable: null,
  350. timeStamp: function (event) {
  351. return event.timeStamp || Date.now();
  352. },
  353. defaultPrevented: null,
  354. isTrusted: null
  355. };
  356. function functionThatReturnsTrue() {
  357. return true;
  358. }
  359. function functionThatReturnsFalse() {
  360. return false;
  361. }
  362. /**
  363. * Synthetic events are dispatched by event plugins, typically in response to a
  364. * top-level event delegation handler.
  365. *
  366. * These systems should generally use pooling to reduce the frequency of garbage
  367. * collection. The system should check `isPersistent` to determine whether the
  368. * event should be released into the pool after being dispatched. Users that
  369. * need a persisted event should invoke `persist`.
  370. *
  371. * Synthetic events (and subclasses) implement the DOM Level 3 Events API by
  372. * normalizing browser quirks. Subclasses do not necessarily have to implement a
  373. * DOM interface; custom application-specific events can also subclass this.
  374. *
  375. * @param {object} dispatchConfig Configuration used to dispatch this event.
  376. * @param {*} targetInst Marker identifying the event target.
  377. * @param {object} nativeEvent Native browser event.
  378. * @param {DOMEventTarget} nativeEventTarget Target node.
  379. */
  380. function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) {
  381. {
  382. // these have a getter/setter for warnings
  383. delete this.nativeEvent;
  384. delete this.preventDefault;
  385. delete this.stopPropagation;
  386. delete this.isDefaultPrevented;
  387. delete this.isPropagationStopped;
  388. }
  389. this.dispatchConfig = dispatchConfig;
  390. this._targetInst = targetInst;
  391. this.nativeEvent = nativeEvent;
  392. var Interface = this.constructor.Interface;
  393. for (var propName in Interface) {
  394. if (!Interface.hasOwnProperty(propName)) {
  395. continue;
  396. }
  397. {
  398. delete this[propName]; // this has a getter/setter for warnings
  399. }
  400. var normalize = Interface[propName];
  401. if (normalize) {
  402. this[propName] = normalize(nativeEvent);
  403. } else {
  404. if (propName === 'target') {
  405. this.target = nativeEventTarget;
  406. } else {
  407. this[propName] = nativeEvent[propName];
  408. }
  409. }
  410. }
  411. var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false;
  412. if (defaultPrevented) {
  413. this.isDefaultPrevented = functionThatReturnsTrue;
  414. } else {
  415. this.isDefaultPrevented = functionThatReturnsFalse;
  416. }
  417. this.isPropagationStopped = functionThatReturnsFalse;
  418. return this;
  419. }
  420. _assign(SyntheticEvent.prototype, {
  421. preventDefault: function () {
  422. this.defaultPrevented = true;
  423. var event = this.nativeEvent;
  424. if (!event) {
  425. return;
  426. }
  427. if (event.preventDefault) {
  428. event.preventDefault();
  429. } else if (typeof event.returnValue !== 'unknown') {
  430. event.returnValue = false;
  431. }
  432. this.isDefaultPrevented = functionThatReturnsTrue;
  433. },
  434. stopPropagation: function () {
  435. var event = this.nativeEvent;
  436. if (!event) {
  437. return;
  438. }
  439. if (event.stopPropagation) {
  440. event.stopPropagation();
  441. } else if (typeof event.cancelBubble !== 'unknown') {
  442. // The ChangeEventPlugin registers a "propertychange" event for
  443. // IE. This event does not support bubbling or cancelling, and
  444. // any references to cancelBubble throw "Member not found". A
  445. // typeof check of "unknown" circumvents this issue (and is also
  446. // IE specific).
  447. event.cancelBubble = true;
  448. }
  449. this.isPropagationStopped = functionThatReturnsTrue;
  450. },
  451. /**
  452. * We release all dispatched `SyntheticEvent`s after each event loop, adding
  453. * them back into the pool. This allows a way to hold onto a reference that
  454. * won't be added back into the pool.
  455. */
  456. persist: function () {
  457. this.isPersistent = functionThatReturnsTrue;
  458. },
  459. /**
  460. * Checks if this event should be released back into the pool.
  461. *
  462. * @return {boolean} True if this should not be released, false otherwise.
  463. */
  464. isPersistent: functionThatReturnsFalse,
  465. /**
  466. * `PooledClass` looks for `destructor` on each instance it releases.
  467. */
  468. destructor: function () {
  469. var Interface = this.constructor.Interface;
  470. for (var propName in Interface) {
  471. {
  472. Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName]));
  473. }
  474. }
  475. this.dispatchConfig = null;
  476. this._targetInst = null;
  477. this.nativeEvent = null;
  478. this.isDefaultPrevented = functionThatReturnsFalse;
  479. this.isPropagationStopped = functionThatReturnsFalse;
  480. this._dispatchListeners = null;
  481. this._dispatchInstances = null;
  482. {
  483. Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null));
  484. Object.defineProperty(this, 'isDefaultPrevented', getPooledWarningPropertyDefinition('isDefaultPrevented', functionThatReturnsFalse));
  485. Object.defineProperty(this, 'isPropagationStopped', getPooledWarningPropertyDefinition('isPropagationStopped', functionThatReturnsFalse));
  486. Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', function () {}));
  487. Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', function () {}));
  488. }
  489. }
  490. });
  491. SyntheticEvent.Interface = EventInterface;
  492. /**
  493. * Helper to reduce boilerplate when creating subclasses.
  494. */
  495. SyntheticEvent.extend = function (Interface) {
  496. var Super = this;
  497. var E = function () {};
  498. E.prototype = Super.prototype;
  499. var prototype = new E();
  500. function Class() {
  501. return Super.apply(this, arguments);
  502. }
  503. _assign(prototype, Class.prototype);
  504. Class.prototype = prototype;
  505. Class.prototype.constructor = Class;
  506. Class.Interface = _assign({}, Super.Interface, Interface);
  507. Class.extend = Super.extend;
  508. addEventPoolingTo(Class);
  509. return Class;
  510. };
  511. addEventPoolingTo(SyntheticEvent);
  512. /**
  513. * Helper to nullify syntheticEvent instance properties when destructing
  514. *
  515. * @param {String} propName
  516. * @param {?object} getVal
  517. * @return {object} defineProperty object
  518. */
  519. function getPooledWarningPropertyDefinition(propName, getVal) {
  520. var isFunction = typeof getVal === 'function';
  521. return {
  522. configurable: true,
  523. set: set,
  524. get: get
  525. };
  526. function set(val) {
  527. var action = isFunction ? 'setting the method' : 'setting the property';
  528. warn(action, 'This is effectively a no-op');
  529. return val;
  530. }
  531. function get() {
  532. var action = isFunction ? 'accessing the method' : 'accessing the property';
  533. var result = isFunction ? 'This is a no-op function' : 'This is set to null';
  534. warn(action, result);
  535. return getVal;
  536. }
  537. function warn(action, result) {
  538. var warningCondition = false;
  539. !warningCondition ? warningWithoutStack$1(false, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0;
  540. }
  541. }
  542. function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) {
  543. var EventConstructor = this;
  544. if (EventConstructor.eventPool.length) {
  545. var instance = EventConstructor.eventPool.pop();
  546. EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst);
  547. return instance;
  548. }
  549. return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst);
  550. }
  551. function releasePooledEvent(event) {
  552. var EventConstructor = this;
  553. if (!(event instanceof EventConstructor)) {
  554. {
  555. throw Error("Trying to release an event instance into a pool of a different type.");
  556. }
  557. }
  558. event.destructor();
  559. if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) {
  560. EventConstructor.eventPool.push(event);
  561. }
  562. }
  563. function addEventPoolingTo(EventConstructor) {
  564. EventConstructor.eventPool = [];
  565. EventConstructor.getPooled = getPooledEvent;
  566. EventConstructor.release = releasePooledEvent;
  567. }
  568. /**
  569. * Forked from fbjs/warning:
  570. * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js
  571. *
  572. * Only change is we use console.warn instead of console.error,
  573. * and do nothing when 'console' is not supported.
  574. * This really simplifies the code.
  575. * ---
  576. * Similar to invariant but only logs a warning if the condition is not met.
  577. * This can be used to log issues in development environments in critical
  578. * paths. Removing the logging code for production environments will keep the
  579. * same logic and follow the same code paths.
  580. */
  581. var lowPriorityWarningWithoutStack = function () {};
  582. {
  583. var printWarning = function (format) {
  584. for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  585. args[_key - 1] = arguments[_key];
  586. }
  587. var argIndex = 0;
  588. var message = 'Warning: ' + format.replace(/%s/g, function () {
  589. return args[argIndex++];
  590. });
  591. if (typeof console !== 'undefined') {
  592. console.warn(message);
  593. }
  594. try {
  595. // --- Welcome to debugging React ---
  596. // This error was thrown as a convenience so that you can use this stack
  597. // to find the callsite that caused this warning to fire.
  598. throw new Error(message);
  599. } catch (x) {}
  600. };
  601. lowPriorityWarningWithoutStack = function (condition, format) {
  602. if (format === undefined) {
  603. throw new Error('`lowPriorityWarningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
  604. }
  605. if (!condition) {
  606. for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
  607. args[_key2 - 2] = arguments[_key2];
  608. }
  609. printWarning.apply(void 0, [format].concat(args));
  610. }
  611. };
  612. }
  613. var lowPriorityWarningWithoutStack$1 = lowPriorityWarningWithoutStack;
  614. /**
  615. * HTML nodeType values that represent the type of the node
  616. */
  617. var ELEMENT_NODE = 1;
  618. // Do not use the below two methods directly!
  619. // Instead use constants exported from DOMTopLevelEventTypes in ReactDOM.
  620. // (It is the only module that is allowed to access these methods.)
  621. function unsafeCastStringToDOMTopLevelType(topLevelType) {
  622. return topLevelType;
  623. }
  624. var canUseDOM = !!(typeof window !== 'undefined' && typeof window.document !== 'undefined' && typeof window.document.createElement !== 'undefined');
  625. /**
  626. * Generate a mapping of standard vendor prefixes using the defined style property and event name.
  627. *
  628. * @param {string} styleProp
  629. * @param {string} eventName
  630. * @returns {object}
  631. */
  632. function makePrefixMap(styleProp, eventName) {
  633. var prefixes = {};
  634. prefixes[styleProp.toLowerCase()] = eventName.toLowerCase();
  635. prefixes['Webkit' + styleProp] = 'webkit' + eventName;
  636. prefixes['Moz' + styleProp] = 'moz' + eventName;
  637. return prefixes;
  638. }
  639. /**
  640. * A list of event names to a configurable list of vendor prefixes.
  641. */
  642. var vendorPrefixes = {
  643. animationend: makePrefixMap('Animation', 'AnimationEnd'),
  644. animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
  645. animationstart: makePrefixMap('Animation', 'AnimationStart'),
  646. transitionend: makePrefixMap('Transition', 'TransitionEnd')
  647. };
  648. /**
  649. * Event names that have already been detected and prefixed (if applicable).
  650. */
  651. var prefixedEventNames = {};
  652. /**
  653. * Element to check for prefixes on.
  654. */
  655. var style = {};
  656. /**
  657. * Bootstrap if a DOM exists.
  658. */
  659. if (canUseDOM) {
  660. style = document.createElement('div').style; // On some platforms, in particular some releases of Android 4.x,
  661. // the un-prefixed "animation" and "transition" properties are defined on the
  662. // style object but the events that fire will still be prefixed, so we need
  663. // to check if the un-prefixed events are usable, and if not remove them from the map.
  664. if (!('AnimationEvent' in window)) {
  665. delete vendorPrefixes.animationend.animation;
  666. delete vendorPrefixes.animationiteration.animation;
  667. delete vendorPrefixes.animationstart.animation;
  668. } // Same as above
  669. if (!('TransitionEvent' in window)) {
  670. delete vendorPrefixes.transitionend.transition;
  671. }
  672. }
  673. /**
  674. * Attempts to determine the correct vendor prefixed event name.
  675. *
  676. * @param {string} eventName
  677. * @returns {string}
  678. */
  679. function getVendorPrefixedEventName(eventName) {
  680. if (prefixedEventNames[eventName]) {
  681. return prefixedEventNames[eventName];
  682. } else if (!vendorPrefixes[eventName]) {
  683. return eventName;
  684. }
  685. var prefixMap = vendorPrefixes[eventName];
  686. for (var styleProp in prefixMap) {
  687. if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) {
  688. return prefixedEventNames[eventName] = prefixMap[styleProp];
  689. }
  690. }
  691. return eventName;
  692. }
  693. /**
  694. * To identify top level events in ReactDOM, we use constants defined by this
  695. * module. This is the only module that uses the unsafe* methods to express
  696. * that the constants actually correspond to the browser event names. This lets
  697. * us save some bundle size by avoiding a top level type -> event name map.
  698. * The rest of ReactDOM code should import top level types from this file.
  699. */
  700. var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
  701. var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
  702. var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'));
  703. var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
  704. var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
  705. var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
  706. var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
  707. var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
  708. var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
  709. var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
  710. var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
  711. var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
  712. var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart');
  713. var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate');
  714. var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
  715. var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
  716. var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
  717. var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
  718. var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
  719. var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
  720. var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
  721. var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
  722. var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
  723. var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
  724. var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
  725. var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
  726. var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
  727. var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
  728. var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
  729. var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
  730. var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
  731. var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
  732. var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
  733. var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
  734. var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
  735. var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
  736. var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
  737. var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
  738. var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
  739. var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
  740. var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
  741. var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
  742. var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
  743. var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
  744. var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
  745. var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
  746. var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
  747. var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
  748. var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
  749. var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
  750. var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
  751. var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
  752. var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
  753. var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
  754. var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
  755. var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
  756. var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
  757. var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
  758. var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
  759. var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
  760. var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
  761. var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
  762. var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
  763. var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
  764. var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
  765. var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
  766. var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
  767. var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); // List of events that need to be individually attached to media elements.
  768. // Note that events in this list will *not* be listened to at the top level
  769. // unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`.
  770. var PLUGIN_EVENT_SYSTEM = 1;
  771. var didWarnAboutMessageChannel = false;
  772. var enqueueTask;
  773. try {
  774. // read require off the module object to get around the bundlers.
  775. // we don't want them to detect a require and bundle a Node polyfill.
  776. var requireString = ('require' + Math.random()).slice(0, 7);
  777. var nodeRequire = module && module[requireString]; // assuming we're in node, let's try to get node's
  778. // version of setImmediate, bypassing fake timers if any.
  779. enqueueTask = nodeRequire('timers').setImmediate;
  780. } catch (_err) {
  781. // we're in a browser
  782. // we can't use regular timers because they may still be faked
  783. // so we try MessageChannel+postMessage instead
  784. enqueueTask = function (callback) {
  785. {
  786. if (didWarnAboutMessageChannel === false) {
  787. didWarnAboutMessageChannel = true;
  788. !(typeof MessageChannel !== 'undefined') ? warningWithoutStack$1(false, 'This browser does not have a MessageChannel implementation, ' + 'so enqueuing tasks via await act(async () => ...) will fail. ' + 'Please file an issue at https://github.com/facebook/react/issues ' + 'if you encounter this warning.') : void 0;
  789. }
  790. }
  791. var channel = new MessageChannel();
  792. channel.port1.onmessage = callback;
  793. channel.port2.postMessage(undefined);
  794. };
  795. }
  796. var enqueueTask$1 = enqueueTask;
  797. // ReactDOM.js, and ReactTestUtils.js:
  798. var _ReactDOM$__SECRET_IN$1 = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events;
  799. var getInstanceFromNode$1 = _ReactDOM$__SECRET_IN$1[0];
  800. var getNodeFromInstance$1 = _ReactDOM$__SECRET_IN$1[1];
  801. var getFiberCurrentPropsFromNode$1 = _ReactDOM$__SECRET_IN$1[2];
  802. var injectEventPluginsByName$1 = _ReactDOM$__SECRET_IN$1[3];
  803. var eventNameDispatchConfigs$1 = _ReactDOM$__SECRET_IN$1[4];
  804. var accumulateTwoPhaseDispatches$1 = _ReactDOM$__SECRET_IN$1[5];
  805. var accumulateDirectDispatches$1 = _ReactDOM$__SECRET_IN$1[6];
  806. var enqueueStateRestore$1 = _ReactDOM$__SECRET_IN$1[7];
  807. var restoreStateIfNeeded$1 = _ReactDOM$__SECRET_IN$1[8];
  808. var dispatchEvent$1 = _ReactDOM$__SECRET_IN$1[9];
  809. var runEventsInBatch$1 = _ReactDOM$__SECRET_IN$1[10];
  810. var flushPassiveEffects$1 = _ReactDOM$__SECRET_IN$1[11];
  811. var IsThisRendererActing$1 = _ReactDOM$__SECRET_IN$1[12];
  812. var batchedUpdates = ReactDOM.unstable_batchedUpdates;
  813. var IsSomeRendererActing = ReactSharedInternals.IsSomeRendererActing; // this implementation should be exactly the same in
  814. // ReactTestUtilsAct.js, ReactTestRendererAct.js, createReactNoop.js
  815. var isSchedulerMocked = typeof Scheduler.unstable_flushAllWithoutAsserting === 'function';
  816. var flushWork = Scheduler.unstable_flushAllWithoutAsserting || function () {
  817. var didFlushWork = false;
  818. while (flushPassiveEffects$1()) {
  819. didFlushWork = true;
  820. }
  821. return didFlushWork;
  822. };
  823. function flushWorkAndMicroTasks(onDone) {
  824. try {
  825. flushWork();
  826. enqueueTask$1(function () {
  827. if (flushWork()) {
  828. flushWorkAndMicroTasks(onDone);
  829. } else {
  830. onDone();
  831. }
  832. });
  833. } catch (err) {
  834. onDone(err);
  835. }
  836. } // we track the 'depth' of the act() calls with this counter,
  837. // so we can tell if any async act() calls try to run in parallel.
  838. var actingUpdatesScopeDepth = 0;
  839. function act(callback) {
  840. var previousActingUpdatesScopeDepth = actingUpdatesScopeDepth;
  841. var previousIsSomeRendererActing;
  842. var previousIsThisRendererActing;
  843. actingUpdatesScopeDepth++;
  844. previousIsSomeRendererActing = IsSomeRendererActing.current;
  845. previousIsThisRendererActing = IsThisRendererActing$1.current;
  846. IsSomeRendererActing.current = true;
  847. IsThisRendererActing$1.current = true;
  848. function onDone() {
  849. actingUpdatesScopeDepth--;
  850. IsSomeRendererActing.current = previousIsSomeRendererActing;
  851. IsThisRendererActing$1.current = previousIsThisRendererActing;
  852. {
  853. if (actingUpdatesScopeDepth > previousActingUpdatesScopeDepth) {
  854. // if it's _less than_ previousActingUpdatesScopeDepth, then we can assume the 'other' one has warned
  855. warningWithoutStack$1(false, 'You seem to have overlapping act() calls, this is not supported. ' + 'Be sure to await previous act() calls before making a new one. ');
  856. }
  857. }
  858. }
  859. var result;
  860. try {
  861. result = batchedUpdates(callback);
  862. } catch (error) {
  863. // on sync errors, we still want to 'cleanup' and decrement actingUpdatesScopeDepth
  864. onDone();
  865. throw error;
  866. }
  867. if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
  868. // setup a boolean that gets set to true only
  869. // once this act() call is await-ed
  870. var called = false;
  871. {
  872. if (typeof Promise !== 'undefined') {
  873. //eslint-disable-next-line no-undef
  874. Promise.resolve().then(function () {}).then(function () {
  875. if (called === false) {
  876. warningWithoutStack$1(false, 'You called act(async () => ...) without await. ' + 'This could lead to unexpected testing behaviour, interleaving multiple act ' + 'calls and mixing their scopes. You should - await act(async () => ...);');
  877. }
  878. });
  879. }
  880. } // in the async case, the returned thenable runs the callback, flushes
  881. // effects and microtasks in a loop until flushPassiveEffects() === false,
  882. // and cleans up
  883. return {
  884. then: function (resolve, reject) {
  885. called = true;
  886. result.then(function () {
  887. if (actingUpdatesScopeDepth > 1 || isSchedulerMocked === true && previousIsSomeRendererActing === true) {
  888. onDone();
  889. resolve();
  890. return;
  891. } // we're about to exit the act() scope,
  892. // now's the time to flush tasks/effects
  893. flushWorkAndMicroTasks(function (err) {
  894. onDone();
  895. if (err) {
  896. reject(err);
  897. } else {
  898. resolve();
  899. }
  900. });
  901. }, function (err) {
  902. onDone();
  903. reject(err);
  904. });
  905. }
  906. };
  907. } else {
  908. {
  909. !(result === undefined) ? warningWithoutStack$1(false, 'The callback passed to act(...) function ' + 'must return undefined, or a Promise. You returned %s', result) : void 0;
  910. } // flush effects until none remain, and cleanup
  911. try {
  912. if (actingUpdatesScopeDepth === 1 && (isSchedulerMocked === false || previousIsSomeRendererActing === false)) {
  913. // we're about to exit the act() scope,
  914. // now's the time to flush effects
  915. flushWork();
  916. }
  917. onDone();
  918. } catch (err) {
  919. onDone();
  920. throw err;
  921. } // in the sync case, the returned thenable only warns *if* await-ed
  922. return {
  923. then: function (resolve) {
  924. {
  925. warningWithoutStack$1(false, 'Do not await the result of calling act(...) with sync logic, it is not a Promise.');
  926. }
  927. resolve();
  928. }
  929. };
  930. }
  931. }
  932. var findDOMNode = ReactDOM.findDOMNode; // Keep in sync with ReactDOMUnstableNativeDependencies.js
  933. // ReactDOM.js, and ReactTestUtilsAct.js:
  934. var _ReactDOM$__SECRET_IN = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events;
  935. var getInstanceFromNode = _ReactDOM$__SECRET_IN[0];
  936. var getNodeFromInstance = _ReactDOM$__SECRET_IN[1];
  937. var getFiberCurrentPropsFromNode = _ReactDOM$__SECRET_IN[2];
  938. var injectEventPluginsByName = _ReactDOM$__SECRET_IN[3];
  939. var eventNameDispatchConfigs = _ReactDOM$__SECRET_IN[4];
  940. var accumulateTwoPhaseDispatches = _ReactDOM$__SECRET_IN[5];
  941. var accumulateDirectDispatches = _ReactDOM$__SECRET_IN[6];
  942. var enqueueStateRestore = _ReactDOM$__SECRET_IN[7];
  943. var restoreStateIfNeeded = _ReactDOM$__SECRET_IN[8];
  944. var dispatchEvent = _ReactDOM$__SECRET_IN[9];
  945. var runEventsInBatch = _ReactDOM$__SECRET_IN[10];
  946. var flushPassiveEffects = _ReactDOM$__SECRET_IN[11];
  947. var IsThisRendererActing = _ReactDOM$__SECRET_IN[12];
  948. function Event(suffix) {}
  949. var hasWarnedAboutDeprecatedMockComponent = false;
  950. /**
  951. * @class ReactTestUtils
  952. */
  953. /**
  954. * Simulates a top level event being dispatched from a raw event that occurred
  955. * on an `Element` node.
  956. * @param {number} topLevelType A number from `TopLevelEventTypes`
  957. * @param {!Element} node The dom to simulate an event occurring on.
  958. * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
  959. */
  960. function simulateNativeEventOnNode(topLevelType, node, fakeNativeEvent) {
  961. fakeNativeEvent.target = node;
  962. dispatchEvent(topLevelType, PLUGIN_EVENT_SYSTEM, fakeNativeEvent);
  963. }
  964. /**
  965. * Simulates a top level event being dispatched from a raw event that occurred
  966. * on the `ReactDOMComponent` `comp`.
  967. * @param {Object} topLevelType A type from `BrowserEventConstants.topLevelTypes`.
  968. * @param {!ReactDOMComponent} comp
  969. * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
  970. */
  971. function simulateNativeEventOnDOMComponent(topLevelType, comp, fakeNativeEvent) {
  972. simulateNativeEventOnNode(topLevelType, findDOMNode(comp), fakeNativeEvent);
  973. }
  974. function findAllInRenderedFiberTreeInternal(fiber, test) {
  975. if (!fiber) {
  976. return [];
  977. }
  978. var currentParent = findCurrentFiberUsingSlowPath(fiber);
  979. if (!currentParent) {
  980. return [];
  981. }
  982. var node = currentParent;
  983. var ret = [];
  984. while (true) {
  985. if (node.tag === HostComponent || node.tag === HostText || node.tag === ClassComponent || node.tag === FunctionComponent) {
  986. var publicInst = node.stateNode;
  987. if (test(publicInst)) {
  988. ret.push(publicInst);
  989. }
  990. }
  991. if (node.child) {
  992. node.child.return = node;
  993. node = node.child;
  994. continue;
  995. }
  996. if (node === currentParent) {
  997. return ret;
  998. }
  999. while (!node.sibling) {
  1000. if (!node.return || node.return === currentParent) {
  1001. return ret;
  1002. }
  1003. node = node.return;
  1004. }
  1005. node.sibling.return = node.return;
  1006. node = node.sibling;
  1007. }
  1008. }
  1009. function validateClassInstance(inst, methodName) {
  1010. if (!inst) {
  1011. // This is probably too relaxed but it's existing behavior.
  1012. return;
  1013. }
  1014. if (get(inst)) {
  1015. // This is a public instance indeed.
  1016. return;
  1017. }
  1018. var received;
  1019. var stringified = '' + inst;
  1020. if (Array.isArray(inst)) {
  1021. received = 'an array';
  1022. } else if (inst && inst.nodeType === ELEMENT_NODE && inst.tagName) {
  1023. received = 'a DOM node';
  1024. } else if (stringified === '[object Object]') {
  1025. received = 'object with keys {' + Object.keys(inst).join(', ') + '}';
  1026. } else {
  1027. received = stringified;
  1028. }
  1029. {
  1030. {
  1031. throw Error(methodName + "(...): the first argument must be a React class instance. Instead received: " + received + ".");
  1032. }
  1033. }
  1034. }
  1035. /**
  1036. * Utilities for making it easy to test React components.
  1037. *
  1038. * See https://reactjs.org/docs/test-utils.html
  1039. *
  1040. * Todo: Support the entire DOM.scry query syntax. For now, these simple
  1041. * utilities will suffice for testing purposes.
  1042. * @lends ReactTestUtils
  1043. */
  1044. var ReactTestUtils = {
  1045. renderIntoDocument: function (element) {
  1046. var div = document.createElement('div'); // None of our tests actually require attaching the container to the
  1047. // DOM, and doing so creates a mess that we rely on test isolation to
  1048. // clean up, so we're going to stop honoring the name of this method
  1049. // (and probably rename it eventually) if no problems arise.
  1050. // document.documentElement.appendChild(div);
  1051. return ReactDOM.render(element, div);
  1052. },
  1053. isElement: function (element) {
  1054. return React.isValidElement(element);
  1055. },
  1056. isElementOfType: function (inst, convenienceConstructor) {
  1057. return React.isValidElement(inst) && inst.type === convenienceConstructor;
  1058. },
  1059. isDOMComponent: function (inst) {
  1060. return !!(inst && inst.nodeType === ELEMENT_NODE && inst.tagName);
  1061. },
  1062. isDOMComponentElement: function (inst) {
  1063. return !!(inst && React.isValidElement(inst) && !!inst.tagName);
  1064. },
  1065. isCompositeComponent: function (inst) {
  1066. if (ReactTestUtils.isDOMComponent(inst)) {
  1067. // Accessing inst.setState warns; just return false as that'll be what
  1068. // this returns when we have DOM nodes as refs directly
  1069. return false;
  1070. }
  1071. return inst != null && typeof inst.render === 'function' && typeof inst.setState === 'function';
  1072. },
  1073. isCompositeComponentWithType: function (inst, type) {
  1074. if (!ReactTestUtils.isCompositeComponent(inst)) {
  1075. return false;
  1076. }
  1077. var internalInstance = get(inst);
  1078. var constructor = internalInstance.type;
  1079. return constructor === type;
  1080. },
  1081. findAllInRenderedTree: function (inst, test) {
  1082. validateClassInstance(inst, 'findAllInRenderedTree');
  1083. if (!inst) {
  1084. return [];
  1085. }
  1086. var internalInstance = get(inst);
  1087. return findAllInRenderedFiberTreeInternal(internalInstance, test);
  1088. },
  1089. /**
  1090. * Finds all instance of components in the rendered tree that are DOM
  1091. * components with the class name matching `className`.
  1092. * @return {array} an array of all the matches.
  1093. */
  1094. scryRenderedDOMComponentsWithClass: function (root, classNames) {
  1095. validateClassInstance(root, 'scryRenderedDOMComponentsWithClass');
  1096. return ReactTestUtils.findAllInRenderedTree(root, function (inst) {
  1097. if (ReactTestUtils.isDOMComponent(inst)) {
  1098. var className = inst.className;
  1099. if (typeof className !== 'string') {
  1100. // SVG, probably.
  1101. className = inst.getAttribute('class') || '';
  1102. }
  1103. var classList = className.split(/\s+/);
  1104. if (!Array.isArray(classNames)) {
  1105. if (!(classNames !== undefined)) {
  1106. {
  1107. throw Error("TestUtils.scryRenderedDOMComponentsWithClass expects a className as a second argument.");
  1108. }
  1109. }
  1110. classNames = classNames.split(/\s+/);
  1111. }
  1112. return classNames.every(function (name) {
  1113. return classList.indexOf(name) !== -1;
  1114. });
  1115. }
  1116. return false;
  1117. });
  1118. },
  1119. /**
  1120. * Like scryRenderedDOMComponentsWithClass but expects there to be one result,
  1121. * and returns that one result, or throws exception if there is any other
  1122. * number of matches besides one.
  1123. * @return {!ReactDOMComponent} The one match.
  1124. */
  1125. findRenderedDOMComponentWithClass: function (root, className) {
  1126. validateClassInstance(root, 'findRenderedDOMComponentWithClass');
  1127. var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className);
  1128. if (all.length !== 1) {
  1129. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for class:' + className);
  1130. }
  1131. return all[0];
  1132. },
  1133. /**
  1134. * Finds all instance of components in the rendered tree that are DOM
  1135. * components with the tag name matching `tagName`.
  1136. * @return {array} an array of all the matches.
  1137. */
  1138. scryRenderedDOMComponentsWithTag: function (root, tagName) {
  1139. validateClassInstance(root, 'scryRenderedDOMComponentsWithTag');
  1140. return ReactTestUtils.findAllInRenderedTree(root, function (inst) {
  1141. return ReactTestUtils.isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase();
  1142. });
  1143. },
  1144. /**
  1145. * Like scryRenderedDOMComponentsWithTag but expects there to be one result,
  1146. * and returns that one result, or throws exception if there is any other
  1147. * number of matches besides one.
  1148. * @return {!ReactDOMComponent} The one match.
  1149. */
  1150. findRenderedDOMComponentWithTag: function (root, tagName) {
  1151. validateClassInstance(root, 'findRenderedDOMComponentWithTag');
  1152. var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName);
  1153. if (all.length !== 1) {
  1154. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for tag:' + tagName);
  1155. }
  1156. return all[0];
  1157. },
  1158. /**
  1159. * Finds all instances of components with type equal to `componentType`.
  1160. * @return {array} an array of all the matches.
  1161. */
  1162. scryRenderedComponentsWithType: function (root, componentType) {
  1163. validateClassInstance(root, 'scryRenderedComponentsWithType');
  1164. return ReactTestUtils.findAllInRenderedTree(root, function (inst) {
  1165. return ReactTestUtils.isCompositeComponentWithType(inst, componentType);
  1166. });
  1167. },
  1168. /**
  1169. * Same as `scryRenderedComponentsWithType` but expects there to be one result
  1170. * and returns that one result, or throws exception if there is any other
  1171. * number of matches besides one.
  1172. * @return {!ReactComponent} The one match.
  1173. */
  1174. findRenderedComponentWithType: function (root, componentType) {
  1175. validateClassInstance(root, 'findRenderedComponentWithType');
  1176. var all = ReactTestUtils.scryRenderedComponentsWithType(root, componentType);
  1177. if (all.length !== 1) {
  1178. throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for componentType:' + componentType);
  1179. }
  1180. return all[0];
  1181. },
  1182. /**
  1183. * Pass a mocked component module to this method to augment it with
  1184. * useful methods that allow it to be used as a dummy React component.
  1185. * Instead of rendering as usual, the component will become a simple
  1186. * <div> containing any provided children.
  1187. *
  1188. * @param {object} module the mock function object exported from a
  1189. * module that defines the component to be mocked
  1190. * @param {?string} mockTagName optional dummy root tag name to return
  1191. * from render method (overrides
  1192. * module.mockTagName if provided)
  1193. * @return {object} the ReactTestUtils object (for chaining)
  1194. */
  1195. mockComponent: function (module, mockTagName) {
  1196. if (!hasWarnedAboutDeprecatedMockComponent) {
  1197. hasWarnedAboutDeprecatedMockComponent = true;
  1198. lowPriorityWarningWithoutStack$1(false, 'ReactTestUtils.mockComponent() is deprecated. ' + 'Use shallow rendering or jest.mock() instead.\n\n' + 'See https://fb.me/test-utils-mock-component for more information.');
  1199. }
  1200. mockTagName = mockTagName || module.mockTagName || 'div';
  1201. module.prototype.render.mockImplementation(function () {
  1202. return React.createElement(mockTagName, null, this.props.children);
  1203. });
  1204. return this;
  1205. },
  1206. nativeTouchData: function (x, y) {
  1207. return {
  1208. touches: [{
  1209. pageX: x,
  1210. pageY: y
  1211. }]
  1212. };
  1213. },
  1214. Simulate: null,
  1215. SimulateNative: {},
  1216. act: act
  1217. };
  1218. /**
  1219. * Exports:
  1220. *
  1221. * - `ReactTestUtils.Simulate.click(Element)`
  1222. * - `ReactTestUtils.Simulate.mouseMove(Element)`
  1223. * - `ReactTestUtils.Simulate.change(Element)`
  1224. * - ... (All keys from event plugin `eventTypes` objects)
  1225. */
  1226. function makeSimulator(eventType) {
  1227. return function (domNode, eventData) {
  1228. if (!!React.isValidElement(domNode)) {
  1229. {
  1230. throw 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.");
  1231. }
  1232. }
  1233. if (!!ReactTestUtils.isCompositeComponent(domNode)) {
  1234. {
  1235. throw 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.");
  1236. }
  1237. }
  1238. var dispatchConfig = eventNameDispatchConfigs[eventType];
  1239. var fakeNativeEvent = new Event();
  1240. fakeNativeEvent.target = domNode;
  1241. fakeNativeEvent.type = eventType.toLowerCase(); // We don't use SyntheticEvent.getPooled in order to not have to worry about
  1242. // properly destroying any properties assigned from `eventData` upon release
  1243. var targetInst = getInstanceFromNode(domNode);
  1244. var event = new SyntheticEvent(dispatchConfig, targetInst, fakeNativeEvent, domNode); // Since we aren't using pooling, always persist the event. This will make
  1245. // sure it's marked and won't warn when setting additional properties.
  1246. event.persist();
  1247. _assign(event, eventData);
  1248. if (dispatchConfig.phasedRegistrationNames) {
  1249. accumulateTwoPhaseDispatches(event);
  1250. } else {
  1251. accumulateDirectDispatches(event);
  1252. }
  1253. ReactDOM.unstable_batchedUpdates(function () {
  1254. // Normally extractEvent enqueues a state restore, but we'll just always
  1255. // do that since we're by-passing it here.
  1256. enqueueStateRestore(domNode);
  1257. runEventsInBatch(event);
  1258. });
  1259. restoreStateIfNeeded();
  1260. };
  1261. }
  1262. function buildSimulators() {
  1263. ReactTestUtils.Simulate = {};
  1264. var eventType;
  1265. for (eventType in eventNameDispatchConfigs) {
  1266. /**
  1267. * @param {!Element|ReactDOMComponent} domComponentOrNode
  1268. * @param {?object} eventData Fake event data to use in SyntheticEvent.
  1269. */
  1270. ReactTestUtils.Simulate[eventType] = makeSimulator(eventType);
  1271. }
  1272. }
  1273. buildSimulators();
  1274. /**
  1275. * Exports:
  1276. *
  1277. * - `ReactTestUtils.SimulateNative.click(Element/ReactDOMComponent)`
  1278. * - `ReactTestUtils.SimulateNative.mouseMove(Element/ReactDOMComponent)`
  1279. * - `ReactTestUtils.SimulateNative.mouseIn/ReactDOMComponent)`
  1280. * - `ReactTestUtils.SimulateNative.mouseOut(Element/ReactDOMComponent)`
  1281. * - ... (All keys from `BrowserEventConstants.topLevelTypes`)
  1282. *
  1283. * Note: Top level event types are a subset of the entire set of handler types
  1284. * (which include a broader set of "synthetic" events). For example, onDragDone
  1285. * is a synthetic event. Except when testing an event plugin or React's event
  1286. * handling code specifically, you probably want to use ReactTestUtils.Simulate
  1287. * to dispatch synthetic events.
  1288. */
  1289. function makeNativeSimulator(eventType, topLevelType) {
  1290. return function (domComponentOrNode, nativeEventData) {
  1291. var fakeNativeEvent = new Event(eventType);
  1292. _assign(fakeNativeEvent, nativeEventData);
  1293. if (ReactTestUtils.isDOMComponent(domComponentOrNode)) {
  1294. simulateNativeEventOnDOMComponent(topLevelType, domComponentOrNode, fakeNativeEvent);
  1295. } else if (domComponentOrNode.tagName) {
  1296. // Will allow on actual dom nodes.
  1297. simulateNativeEventOnNode(topLevelType, domComponentOrNode, fakeNativeEvent);
  1298. }
  1299. };
  1300. }
  1301. [[TOP_ABORT, 'abort'], [TOP_ANIMATION_END, 'animationEnd'], [TOP_ANIMATION_ITERATION, 'animationIteration'], [TOP_ANIMATION_START, 'animationStart'], [TOP_BLUR, 'blur'], [TOP_CAN_PLAY_THROUGH, 'canPlayThrough'], [TOP_CAN_PLAY, 'canPlay'], [TOP_CANCEL, 'cancel'], [TOP_CHANGE, 'change'], [TOP_CLICK, 'click'], [TOP_CLOSE, 'close'], [TOP_COMPOSITION_END, 'compositionEnd'], [TOP_COMPOSITION_START, 'compositionStart'], [TOP_COMPOSITION_UPDATE, 'compositionUpdate'], [TOP_CONTEXT_MENU, 'contextMenu'], [TOP_COPY, 'copy'], [TOP_CUT, 'cut'], [TOP_DOUBLE_CLICK, 'doubleClick'], [TOP_DRAG_END, 'dragEnd'], [TOP_DRAG_ENTER, 'dragEnter'], [TOP_DRAG_EXIT, 'dragExit'], [TOP_DRAG_LEAVE, 'dragLeave'], [TOP_DRAG_OVER, 'dragOver'], [TOP_DRAG_START, 'dragStart'], [TOP_DRAG, 'drag'], [TOP_DROP, 'drop'], [TOP_DURATION_CHANGE, 'durationChange'], [TOP_EMPTIED, 'emptied'], [TOP_ENCRYPTED, 'encrypted'], [TOP_ENDED, 'ended'], [TOP_ERROR, 'error'], [TOP_FOCUS, 'focus'], [TOP_INPUT, 'input'], [TOP_KEY_DOWN, 'keyDown'], [TOP_KEY_PRESS, 'keyPress'], [TOP_KEY_UP, 'keyUp'], [TOP_LOAD_START, 'loadStart'], [TOP_LOAD_START, 'loadStart'], [TOP_LOAD, 'load'], [TOP_LOADED_DATA, 'loadedData'], [TOP_LOADED_METADATA, 'loadedMetadata'], [TOP_MOUSE_DOWN, 'mouseDown'], [TOP_MOUSE_MOVE, 'mouseMove'], [TOP_MOUSE_OUT, 'mouseOut'], [TOP_MOUSE_OVER, 'mouseOver'], [TOP_MOUSE_UP, 'mouseUp'], [TOP_PASTE, 'paste'], [TOP_PAUSE, 'pause'], [TOP_PLAY, 'play'], [TOP_PLAYING, 'playing'], [TOP_PROGRESS, 'progress'], [TOP_RATE_CHANGE, 'rateChange'], [TOP_SCROLL, 'scroll'], [TOP_SEEKED, 'seeked'], [TOP_SEEKING, 'seeking'], [TOP_SELECTION_CHANGE, 'selectionChange'], [TOP_STALLED, 'stalled'], [TOP_SUSPEND, 'suspend'], [TOP_TEXT_INPUT, 'textInput'], [TOP_TIME_UPDATE, 'timeUpdate'], [TOP_TOGGLE, 'toggle'], [TOP_TOUCH_CANCEL, 'touchCancel'], [TOP_TOUCH_END, 'touchEnd'], [TOP_TOUCH_MOVE, 'touchMove'], [TOP_TOUCH_START, 'touchStart'], [TOP_TRANSITION_END, 'transitionEnd'], [TOP_VOLUME_CHANGE, 'volumeChange'], [TOP_WAITING, 'waiting'], [TOP_WHEEL, 'wheel']].forEach(function (_ref) {
  1302. var topLevelType = _ref[0],
  1303. eventType = _ref[1];
  1304. /**
  1305. * @param {!Element|ReactDOMComponent} domComponentOrNode
  1306. * @param {?Event} nativeEventData Fake native event to use in SyntheticEvent.
  1307. */
  1308. ReactTestUtils.SimulateNative[eventType] = makeNativeSimulator(eventType, topLevelType);
  1309. });
  1310. var ReactTestUtils$2 = Object.freeze({
  1311. default: ReactTestUtils
  1312. });
  1313. var ReactTestUtils$3 = ( ReactTestUtils$2 && ReactTestUtils ) || ReactTestUtils$2;
  1314. // TODO: decide on the top-level export form.
  1315. // This is hacky but makes it work with both Rollup and Jest.
  1316. var testUtils = ReactTestUtils$3.default || ReactTestUtils$3;
  1317. module.exports = testUtils;
  1318. })();
  1319. }