UNPKG

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