UNPKG

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