UNPKG

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