/assets/public/js/react/v16.3.1/react-dom-test-utils.development.js

https://github.com/douyu/juno · JavaScript · 1499 lines · 947 code · 248 blank · 304 comment · 154 complexity · b589a2f224d357ac09934cfb3a008c5b MD5 · raw file

Large files are truncated click here to view the full file

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