UNPKG

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