UNPKG

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