react-dom-test-utils.mjs (41355B)
1 /** @license React v16.8.6 2 * react-dom-test-utils.production.min.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 import React from 'resource://devtools/client/shared/vendor/react.mjs'; 10 import ReactDOM from 'resource://devtools/client/shared/vendor/react-dom.mjs'; 11 12 var ReactInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; 13 14 var _assign = ReactInternals.assign; 15 16 /** 17 * Use invariant() to assert state which your program assumes to be true. 18 * 19 * Provide sprintf-style format (only %s is supported) and arguments 20 * to provide information about what broke and what you were 21 * expecting. 22 * 23 * The invariant message will be stripped in production, but the invariant 24 * will remain to ensure logic does not differ in production. 25 */ 26 27 function invariant(condition, format, a, b, c, d, e, f) { 28 if (!condition) { 29 var error = void 0; 30 if (format === undefined) { 31 error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); 32 } else { 33 var args = [a, b, c, d, e, f]; 34 var argIndex = 0; 35 error = new Error(format.replace(/%s/g, function () { 36 return args[argIndex++]; 37 })); 38 error.name = 'Invariant Violation'; 39 } 40 41 error.framesToPop = 1; // we don't care about invariant's own frame 42 throw error; 43 } 44 } 45 46 // Relying on the `invariant()` implementation lets us 47 // preserve the format and params in the www builds. 48 /** 49 * WARNING: DO NOT manually require this module. 50 * This is a replacement for `invariant(...)` used by the error code system 51 * and will _only_ be required by the corresponding babel pass. 52 * It always throws. 53 */ 54 function reactProdInvariant(code) { 55 var argCount = arguments.length - 1; 56 var url = 'https://reactjs.org/docs/error-decoder.html?invariant=' + code; 57 for (var argIdx = 0; argIdx < argCount; argIdx++) { 58 url += '&args[]=' + encodeURIComponent(arguments[argIdx + 1]); 59 } 60 // Rename it so that our build transform doesn't attempt 61 // to replace this invariant() call with reactProdInvariant(). 62 var i = invariant; 63 i(false, 64 // The error code is intentionally part of the message (and 65 // not the format argument) so that we could deduplicate 66 // different errors in logs based on the code. 67 'Minified React error #' + code + '; visit %s ' + 'for the full message or use the non-minified dev environment ' + 'for full errors and additional helpful warnings. ', url); 68 } 69 70 /** 71 * Similar to invariant but only logs a warning if the condition is not met. 72 * This can be used to log issues in development environments in critical 73 * paths. Removing the logging code for production environments will keep the 74 * same logic and follow the same code paths. 75 */ 76 77 /** 78 * `ReactInstanceMap` maintains a mapping from a public facing stateful 79 * instance (key) and the internal representation (value). This allows public 80 * methods to accept the user facing instance as an argument and map them back 81 * to internal methods. 82 * 83 * Note that this module is currently shared and assumed to be stateless. 84 * If this becomes an actual Map, that will break. 85 */ 86 87 /** 88 * This API should be called `delete` but we'd have to make sure to always 89 * transform these to strings for IE support. When this transform is fully 90 * supported we can rename it. 91 */ 92 93 94 function get(key) { 95 return key._reactInternalFiber; 96 } 97 98 var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; 99 100 // Prevent newer renderers from RTE when used with older react package versions. 101 // Current owner and dispatcher used to share the same ref, 102 // but PR #14548 split them out to better support the react-debug-tools package. 103 if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) { 104 ReactSharedInternals.ReactCurrentDispatcher = { 105 current: null 106 }; 107 } 108 109 // The Symbol used to tag the ReactElement-like types. If there is no native Symbol 110 // nor polyfill, then a plain number is used for performance. 111 112 var FunctionComponent = 0; 113 var ClassComponent = 1; 114 // Before we know whether it is function or class 115 var HostRoot = 3; // Root of a host tree. Could be nested inside another node. 116 // A subtree. Could be an entry point to a different renderer. 117 var HostComponent = 5; 118 var HostText = 6; 119 120 // Don't change these two values. They're used by React Dev Tools. 121 var NoEffect = /* */0; 122 123 124 // You can change the rest (and add more). 125 var Placement = /* */2; 126 127 128 129 130 131 132 133 134 135 136 // Passive & Update & Callback & Ref & Snapshot 137 138 139 // Union of all host effects 140 141 var ReactCurrentOwner = ReactSharedInternals.ReactCurrentOwner; 142 143 var MOUNTING = 1; 144 var MOUNTED = 2; 145 var UNMOUNTED = 3; 146 147 function isFiberMountedImpl(fiber) { 148 var node = fiber; 149 if (!fiber.alternate) { 150 // If there is no alternate, this might be a new tree that isn't inserted 151 // yet. If it is, then it will have a pending insertion effect on it. 152 if ((node.effectTag & Placement) !== NoEffect) { 153 return MOUNTING; 154 } 155 while (node.return) { 156 node = node.return; 157 if ((node.effectTag & Placement) !== NoEffect) { 158 return MOUNTING; 159 } 160 } 161 } else { 162 while (node.return) { 163 node = node.return; 164 } 165 } 166 if (node.tag === HostRoot) { 167 // TODO: Check if this was a nested HostRoot when used with 168 // renderContainerIntoSubtree. 169 return MOUNTED; 170 } 171 // If we didn't hit the root, that means that we're in an disconnected tree 172 // that has been unmounted. 173 return UNMOUNTED; 174 } 175 176 177 178 179 180 function assertIsMounted(fiber) { 181 !(isFiberMountedImpl(fiber) === MOUNTED) ? reactProdInvariant('188') : void 0; 182 } 183 184 function findCurrentFiberUsingSlowPath(fiber) { 185 var alternate = fiber.alternate; 186 if (!alternate) { 187 // If there is no alternate, then we only need to check if it is mounted. 188 var state = isFiberMountedImpl(fiber); 189 !(state !== UNMOUNTED) ? reactProdInvariant('188') : void 0; 190 if (state === MOUNTING) { 191 return null; 192 } 193 return fiber; 194 } 195 // If we have two possible branches, we'll walk backwards up to the root 196 // to see what path the root points to. On the way we may hit one of the 197 // special cases and we'll deal with them. 198 var a = fiber; 199 var b = alternate; 200 while (true) { 201 var parentA = a.return; 202 var parentB = parentA ? parentA.alternate : null; 203 if (!parentA || !parentB) { 204 // We're at the root. 205 break; 206 } 207 208 // If both copies of the parent fiber point to the same child, we can 209 // assume that the child is current. This happens when we bailout on low 210 // priority: the bailed out fiber's child reuses the current child. 211 if (parentA.child === parentB.child) { 212 var child = parentA.child; 213 while (child) { 214 if (child === a) { 215 // We've determined that A is the current branch. 216 assertIsMounted(parentA); 217 return fiber; 218 } 219 if (child === b) { 220 // We've determined that B is the current branch. 221 assertIsMounted(parentA); 222 return alternate; 223 } 224 child = child.sibling; 225 } 226 // We should never have an alternate for any mounting node. So the only 227 // way this could possibly happen is if this was unmounted, if at all. 228 reactProdInvariant('188'); 229 } 230 231 if (a.return !== b.return) { 232 // The return pointer of A and the return pointer of B point to different 233 // fibers. We assume that return pointers never criss-cross, so A must 234 // belong to the child set of A.return, and B must belong to the child 235 // set of B.return. 236 a = parentA; 237 b = parentB; 238 } else { 239 // The return pointers point to the same fiber. We'll have to use the 240 // default, slow path: scan the child sets of each parent alternate to see 241 // which child belongs to which set. 242 // 243 // Search parent A's child set 244 var didFindChild = false; 245 var _child = parentA.child; 246 while (_child) { 247 if (_child === a) { 248 didFindChild = true; 249 a = parentA; 250 b = parentB; 251 break; 252 } 253 if (_child === b) { 254 didFindChild = true; 255 b = parentA; 256 a = parentB; 257 break; 258 } 259 _child = _child.sibling; 260 } 261 if (!didFindChild) { 262 // Search parent B's child set 263 _child = parentB.child; 264 while (_child) { 265 if (_child === a) { 266 didFindChild = true; 267 a = parentB; 268 b = parentA; 269 break; 270 } 271 if (_child === b) { 272 didFindChild = true; 273 b = parentB; 274 a = parentA; 275 break; 276 } 277 _child = _child.sibling; 278 } 279 !didFindChild ? reactProdInvariant('189') : void 0; 280 } 281 } 282 283 !(a.alternate === b) ? reactProdInvariant('190') : void 0; 284 } 285 // If the root is not a host container, we're in a disconnected tree. I.e. 286 // unmounted. 287 !(a.tag === HostRoot) ? reactProdInvariant('188') : void 0; 288 if (a.stateNode.current === a) { 289 // We've determined that A is the current branch. 290 return fiber; 291 } 292 // Otherwise B has to be current branch. 293 return alternate; 294 } 295 296 /* eslint valid-typeof: 0 */ 297 298 var EVENT_POOL_SIZE = 10; 299 300 /** 301 * @interface Event 302 * @see http://www.w3.org/TR/DOM-Level-3-Events/ 303 */ 304 var EventInterface = { 305 type: null, 306 target: null, 307 // currentTarget is set when dispatching; no use in copying it here 308 currentTarget: function () { 309 return null; 310 }, 311 eventPhase: null, 312 bubbles: null, 313 cancelable: null, 314 timeStamp: function (event) { 315 return event.timeStamp || Date.now(); 316 }, 317 defaultPrevented: null, 318 isTrusted: null 319 }; 320 321 function functionThatReturnsTrue() { 322 return true; 323 } 324 325 function functionThatReturnsFalse() { 326 return false; 327 } 328 329 /** 330 * Synthetic events are dispatched by event plugins, typically in response to a 331 * top-level event delegation handler. 332 * 333 * These systems should generally use pooling to reduce the frequency of garbage 334 * collection. The system should check `isPersistent` to determine whether the 335 * event should be released into the pool after being dispatched. Users that 336 * need a persisted event should invoke `persist`. 337 * 338 * Synthetic events (and subclasses) implement the DOM Level 3 Events API by 339 * normalizing browser quirks. Subclasses do not necessarily have to implement a 340 * DOM interface; custom application-specific events can also subclass this. 341 * 342 * @param {object} dispatchConfig Configuration used to dispatch this event. 343 * @param {*} targetInst Marker identifying the event target. 344 * @param {object} nativeEvent Native browser event. 345 * @param {DOMEventTarget} nativeEventTarget Target node. 346 */ 347 function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { 348 this.dispatchConfig = dispatchConfig; 349 this._targetInst = targetInst; 350 this.nativeEvent = nativeEvent; 351 352 var Interface = this.constructor.Interface; 353 for (var propName in Interface) { 354 if (!Interface.hasOwnProperty(propName)) { 355 continue; 356 } 357 var normalize = Interface[propName]; 358 if (normalize) { 359 this[propName] = normalize(nativeEvent); 360 } else { 361 if (propName === 'target') { 362 this.target = nativeEventTarget; 363 } else { 364 this[propName] = nativeEvent[propName]; 365 } 366 } 367 } 368 369 var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; 370 if (defaultPrevented) { 371 this.isDefaultPrevented = functionThatReturnsTrue; 372 } else { 373 this.isDefaultPrevented = functionThatReturnsFalse; 374 } 375 this.isPropagationStopped = functionThatReturnsFalse; 376 return this; 377 } 378 379 _assign(SyntheticEvent.prototype, { 380 preventDefault: function () { 381 this.defaultPrevented = true; 382 var event = this.nativeEvent; 383 if (!event) { 384 return; 385 } 386 387 if (event.preventDefault) { 388 event.preventDefault(); 389 } else if (typeof event.returnValue !== 'unknown') { 390 event.returnValue = false; 391 } 392 this.isDefaultPrevented = functionThatReturnsTrue; 393 }, 394 395 stopPropagation: function () { 396 var event = this.nativeEvent; 397 if (!event) { 398 return; 399 } 400 401 if (event.stopPropagation) { 402 event.stopPropagation(); 403 } else if (typeof event.cancelBubble !== 'unknown') { 404 // The ChangeEventPlugin registers a "propertychange" event for 405 // IE. This event does not support bubbling or cancelling, and 406 // any references to cancelBubble throw "Member not found". A 407 // typeof check of "unknown" circumvents this issue (and is also 408 // IE specific). 409 event.cancelBubble = true; 410 } 411 412 this.isPropagationStopped = functionThatReturnsTrue; 413 }, 414 415 /** 416 * We release all dispatched `SyntheticEvent`s after each event loop, adding 417 * them back into the pool. This allows a way to hold onto a reference that 418 * won't be added back into the pool. 419 */ 420 persist: function () { 421 this.isPersistent = functionThatReturnsTrue; 422 }, 423 424 /** 425 * Checks if this event should be released back into the pool. 426 * 427 * @return {boolean} True if this should not be released, false otherwise. 428 */ 429 isPersistent: functionThatReturnsFalse, 430 431 /** 432 * `PooledClass` looks for `destructor` on each instance it releases. 433 */ 434 destructor: function () { 435 var Interface = this.constructor.Interface; 436 for (var propName in Interface) { 437 { 438 this[propName] = null; 439 } 440 } 441 this.dispatchConfig = null; 442 this._targetInst = null; 443 this.nativeEvent = null; 444 this.isDefaultPrevented = functionThatReturnsFalse; 445 this.isPropagationStopped = functionThatReturnsFalse; 446 this._dispatchListeners = null; 447 this._dispatchInstances = null; 448 449 } 450 }); 451 452 SyntheticEvent.Interface = EventInterface; 453 454 /** 455 * Helper to reduce boilerplate when creating subclasses. 456 */ 457 SyntheticEvent.extend = function (Interface) { 458 var Super = this; 459 460 var E = function () {}; 461 E.prototype = Super.prototype; 462 var prototype = new E(); 463 464 function Class() { 465 return Super.apply(this, arguments); 466 } 467 _assign(prototype, Class.prototype); 468 Class.prototype = prototype; 469 Class.prototype.constructor = Class; 470 471 Class.Interface = _assign({}, Super.Interface, Interface); 472 Class.extend = Super.extend; 473 addEventPoolingTo(Class); 474 475 return Class; 476 }; 477 478 addEventPoolingTo(SyntheticEvent); 479 480 function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { 481 var EventConstructor = this; 482 if (EventConstructor.eventPool.length) { 483 var instance = EventConstructor.eventPool.pop(); 484 EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst); 485 return instance; 486 } 487 return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst); 488 } 489 490 function releasePooledEvent(event) { 491 var EventConstructor = this; 492 !(event instanceof EventConstructor) ? reactProdInvariant('279') : void 0; 493 event.destructor(); 494 if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) { 495 EventConstructor.eventPool.push(event); 496 } 497 } 498 499 function addEventPoolingTo(EventConstructor) { 500 EventConstructor.eventPool = []; 501 EventConstructor.getPooled = getPooledEvent; 502 EventConstructor.release = releasePooledEvent; 503 } 504 505 /** 506 * Forked from fbjs/warning: 507 * https://github.com/facebook/fbjs/blob/e66ba20ad5be433eb54423f2b097d829324d9de6/packages/fbjs/src/__forks__/warning.js 508 * 509 * Only change is we use console.warn instead of console.error, 510 * and do nothing when 'console' is not supported. 511 * This really simplifies the code. 512 * --- 513 * Similar to invariant but only logs a warning if the condition is not met. 514 * This can be used to log issues in development environments in critical 515 * paths. Removing the logging code for production environments will keep the 516 * same logic and follow the same code paths. 517 */ 518 519 /** 520 * HTML nodeType values that represent the type of the node 521 */ 522 523 var ELEMENT_NODE = 1; 524 525 // Do not uses the below two methods directly! 526 // Instead use constants exported from DOMTopLevelEventTypes in ReactDOM. 527 // (It is the only module that is allowed to access these methods.) 528 529 function unsafeCastStringToDOMTopLevelType(topLevelType) { 530 return topLevelType; 531 } 532 533 var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); 534 535 /** 536 * Generate a mapping of standard vendor prefixes using the defined style property and event name. 537 * 538 * @param {string} styleProp 539 * @param {string} eventName 540 * @returns {object} 541 */ 542 function makePrefixMap(styleProp, eventName) { 543 var prefixes = {}; 544 545 prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); 546 prefixes['Webkit' + styleProp] = 'webkit' + eventName; 547 prefixes['Moz' + styleProp] = 'moz' + eventName; 548 549 return prefixes; 550 } 551 552 /** 553 * A list of event names to a configurable list of vendor prefixes. 554 */ 555 var vendorPrefixes = { 556 animationend: makePrefixMap('Animation', 'AnimationEnd'), 557 animationiteration: makePrefixMap('Animation', 'AnimationIteration'), 558 animationstart: makePrefixMap('Animation', 'AnimationStart'), 559 transitionend: makePrefixMap('Transition', 'TransitionEnd') 560 }; 561 562 /** 563 * Event names that have already been detected and prefixed (if applicable). 564 */ 565 var prefixedEventNames = {}; 566 567 /** 568 * Element to check for prefixes on. 569 */ 570 var style = {}; 571 572 /** 573 * Bootstrap if a DOM exists. 574 */ 575 if (canUseDOM) { 576 style = document.createElementNS('http://www.w3.org/1999/xhtml', 'div').style; 577 578 // On some platforms, in particular some releases of Android 4.x, 579 // the un-prefixed "animation" and "transition" properties are defined on the 580 // style object but the events that fire will still be prefixed, so we need 581 // to check if the un-prefixed events are usable, and if not remove them from the map. 582 if (!('AnimationEvent' in window)) { 583 delete vendorPrefixes.animationend.animation; 584 delete vendorPrefixes.animationiteration.animation; 585 delete vendorPrefixes.animationstart.animation; 586 } 587 588 // Same as above 589 if (!('TransitionEvent' in window)) { 590 delete vendorPrefixes.transitionend.transition; 591 } 592 } 593 594 /** 595 * Attempts to determine the correct vendor prefixed event name. 596 * 597 * @param {string} eventName 598 * @returns {string} 599 */ 600 function getVendorPrefixedEventName(eventName) { 601 if (prefixedEventNames[eventName]) { 602 return prefixedEventNames[eventName]; 603 } else if (!vendorPrefixes[eventName]) { 604 return eventName; 605 } 606 607 var prefixMap = vendorPrefixes[eventName]; 608 609 for (var styleProp in prefixMap) { 610 if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { 611 return prefixedEventNames[eventName] = prefixMap[styleProp]; 612 } 613 } 614 615 return eventName; 616 } 617 618 /** 619 * To identify top level events in ReactDOM, we use constants defined by this 620 * module. This is the only module that uses the unsafe* methods to express 621 * that the constants actually correspond to the browser event names. This lets 622 * us save some bundle size by avoiding a top level type -> event name map. 623 * The rest of ReactDOM code should import top level types from this file. 624 */ 625 var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort'); 626 var TOP_ANIMATION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend')); 627 var TOP_ANIMATION_ITERATION = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration')); 628 var TOP_ANIMATION_START = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart')); 629 var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur'); 630 var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay'); 631 var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough'); 632 var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel'); 633 var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change'); 634 var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click'); 635 var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close'); 636 var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend'); 637 var TOP_COMPOSITION_START = unsafeCastStringToDOMTopLevelType('compositionstart'); 638 var TOP_COMPOSITION_UPDATE = unsafeCastStringToDOMTopLevelType('compositionupdate'); 639 var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu'); 640 var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy'); 641 var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut'); 642 var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick'); 643 644 var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag'); 645 var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend'); 646 var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter'); 647 var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit'); 648 var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave'); 649 var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover'); 650 var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart'); 651 var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop'); 652 var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange'); 653 var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied'); 654 var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted'); 655 var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended'); 656 var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error'); 657 var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus'); 658 659 var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input'); 660 661 var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown'); 662 var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress'); 663 var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup'); 664 var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load'); 665 var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart'); 666 var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata'); 667 var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata'); 668 669 var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown'); 670 var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove'); 671 var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout'); 672 var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover'); 673 var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup'); 674 var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste'); 675 var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause'); 676 var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play'); 677 var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing'); 678 679 680 681 682 683 684 685 686 var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress'); 687 var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange'); 688 689 var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll'); 690 var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked'); 691 var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking'); 692 var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange'); 693 var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled'); 694 695 var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend'); 696 var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput'); 697 var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate'); 698 var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle'); 699 var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel'); 700 var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend'); 701 var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove'); 702 var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart'); 703 var TOP_TRANSITION_END = unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend')); 704 var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange'); 705 var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting'); 706 var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); 707 708 // List of events that need to be individually attached to media elements. 709 // Note that events in this list will *not* be listened to at the top level 710 // unless they're explicitly whitelisted in `ReactBrowserEventEmitter.listenTo`. 711 712 // for .act's return value 713 var findDOMNode = ReactDOM.findDOMNode; 714 // Keep in sync with ReactDOMUnstableNativeDependencies.js 715 // and ReactDOM.js: 716 717 var _ReactDOM$__SECRET_IN = ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events; 718 var getInstanceFromNode = _ReactDOM$__SECRET_IN[0]; 719 var getNodeFromInstance = _ReactDOM$__SECRET_IN[1]; 720 var getFiberCurrentPropsFromNode = _ReactDOM$__SECRET_IN[2]; 721 var injectEventPluginsByName = _ReactDOM$__SECRET_IN[3]; 722 var eventNameDispatchConfigs = _ReactDOM$__SECRET_IN[4]; 723 var accumulateTwoPhaseDispatches = _ReactDOM$__SECRET_IN[5]; 724 var accumulateDirectDispatches = _ReactDOM$__SECRET_IN[6]; 725 var enqueueStateRestore = _ReactDOM$__SECRET_IN[7]; 726 var restoreStateIfNeeded = _ReactDOM$__SECRET_IN[8]; 727 var dispatchEvent = _ReactDOM$__SECRET_IN[9]; 728 var runEventsInBatch = _ReactDOM$__SECRET_IN[10]; 729 730 731 function Event(suffix) {} 732 733 /** 734 * @class ReactTestUtils 735 */ 736 737 /** 738 * Simulates a top level event being dispatched from a raw event that occurred 739 * on an `Element` node. 740 * @param {number} topLevelType A number from `TopLevelEventTypes` 741 * @param {!Element} node The dom to simulate an event occurring on. 742 * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. 743 */ 744 function simulateNativeEventOnNode(topLevelType, node, fakeNativeEvent) { 745 fakeNativeEvent.target = node; 746 dispatchEvent(topLevelType, fakeNativeEvent); 747 } 748 749 /** 750 * Simulates a top level event being dispatched from a raw event that occurred 751 * on the `ReactDOMComponent` `comp`. 752 * @param {Object} topLevelType A type from `BrowserEventConstants.topLevelTypes`. 753 * @param {!ReactDOMComponent} comp 754 * @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent. 755 */ 756 function simulateNativeEventOnDOMComponent(topLevelType, comp, fakeNativeEvent) { 757 simulateNativeEventOnNode(topLevelType, findDOMNode(comp), fakeNativeEvent); 758 } 759 760 function findAllInRenderedFiberTreeInternal(fiber, test) { 761 if (!fiber) { 762 return []; 763 } 764 var currentParent = findCurrentFiberUsingSlowPath(fiber); 765 if (!currentParent) { 766 return []; 767 } 768 var node = currentParent; 769 var ret = []; 770 while (true) { 771 if (node.tag === HostComponent || node.tag === HostText || node.tag === ClassComponent || node.tag === FunctionComponent) { 772 var publicInst = node.stateNode; 773 if (test(publicInst)) { 774 ret.push(publicInst); 775 } 776 } 777 if (node.child) { 778 node.child.return = node; 779 node = node.child; 780 continue; 781 } 782 if (node === currentParent) { 783 return ret; 784 } 785 while (!node.sibling) { 786 if (!node.return || node.return === currentParent) { 787 return ret; 788 } 789 node = node.return; 790 } 791 node.sibling.return = node.return; 792 node = node.sibling; 793 } 794 } 795 796 function validateClassInstance(inst, methodName) { 797 if (!inst) { 798 // This is probably too relaxed but it's existing behavior. 799 return; 800 } 801 if (get(inst)) { 802 // This is a public instance indeed. 803 return; 804 } 805 var received = void 0; 806 var stringified = '' + inst; 807 if (Array.isArray(inst)) { 808 received = 'an array'; 809 } else if (inst && inst.nodeType === ELEMENT_NODE && inst.tagName) { 810 received = 'a DOM node'; 811 } else if (stringified === '[object Object]') { 812 received = 'object with keys {' + Object.keys(inst).join(', ') + '}'; 813 } else { 814 received = stringified; 815 } 816 reactProdInvariant('286', methodName, received); 817 } 818 819 // a stub element, lazily initialized, used by act() when flushing effects 820 var actContainerElement = null; 821 822 /** 823 * Utilities for making it easy to test React components. 824 * 825 * See https://reactjs.org/docs/test-utils.html 826 * 827 * Todo: Support the entire DOM.scry query syntax. For now, these simple 828 * utilities will suffice for testing purposes. 829 * @lends ReactTestUtils 830 */ 831 var ReactTestUtils = { 832 renderIntoDocument: function (element) { 833 var div = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); 834 // None of our tests actually require attaching the container to the 835 // DOM, and doing so creates a mess that we rely on test isolation to 836 // clean up, so we're going to stop honoring the name of this method 837 // (and probably rename it eventually) if no problems arise. 838 // document.documentElement.appendChild(div); 839 return ReactDOM.render(element, div); 840 }, 841 842 isElement: function (element) { 843 return React.isValidElement(element); 844 }, 845 846 isElementOfType: function (inst, convenienceConstructor) { 847 return React.isValidElement(inst) && inst.type === convenienceConstructor; 848 }, 849 850 isDOMComponent: function (inst) { 851 return !!(inst && inst.nodeType === ELEMENT_NODE && inst.tagName); 852 }, 853 854 isDOMComponentElement: function (inst) { 855 return !!(inst && React.isValidElement(inst) && !!inst.tagName); 856 }, 857 858 isCompositeComponent: function (inst) { 859 if (ReactTestUtils.isDOMComponent(inst)) { 860 // Accessing inst.setState warns; just return false as that'll be what 861 // this returns when we have DOM nodes as refs directly 862 return false; 863 } 864 return inst != null && typeof inst.render === 'function' && typeof inst.setState === 'function'; 865 }, 866 867 isCompositeComponentWithType: function (inst, type) { 868 if (!ReactTestUtils.isCompositeComponent(inst)) { 869 return false; 870 } 871 var internalInstance = get(inst); 872 var constructor = internalInstance.type; 873 return constructor === type; 874 }, 875 876 findAllInRenderedTree: function (inst, test) { 877 validateClassInstance(inst, 'findAllInRenderedTree'); 878 if (!inst) { 879 return []; 880 } 881 var internalInstance = get(inst); 882 return findAllInRenderedFiberTreeInternal(internalInstance, test); 883 }, 884 885 /** 886 * Finds all instance of components in the rendered tree that are DOM 887 * components with the class name matching `className`. 888 * @return {array} an array of all the matches. 889 */ 890 scryRenderedDOMComponentsWithClass: function (root, classNames) { 891 validateClassInstance(root, 'scryRenderedDOMComponentsWithClass'); 892 return ReactTestUtils.findAllInRenderedTree(root, function (inst) { 893 if (ReactTestUtils.isDOMComponent(inst)) { 894 var className = inst.className; 895 if (typeof className !== 'string') { 896 // SVG, probably. 897 className = inst.getAttribute('class') || ''; 898 } 899 var classList = className.split(/\s+/); 900 901 if (!Array.isArray(classNames)) { 902 !(classNames !== undefined) ? reactProdInvariant('11') : void 0; 903 classNames = classNames.split(/\s+/); 904 } 905 return classNames.every(function (name) { 906 return classList.indexOf(name) !== -1; 907 }); 908 } 909 return false; 910 }); 911 }, 912 913 /** 914 * Like scryRenderedDOMComponentsWithClass but expects there to be one result, 915 * and returns that one result, or throws exception if there is any other 916 * number of matches besides one. 917 * @return {!ReactDOMComponent} The one match. 918 */ 919 findRenderedDOMComponentWithClass: function (root, className) { 920 validateClassInstance(root, 'findRenderedDOMComponentWithClass'); 921 var all = ReactTestUtils.scryRenderedDOMComponentsWithClass(root, className); 922 if (all.length !== 1) { 923 throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for class:' + className); 924 } 925 return all[0]; 926 }, 927 928 /** 929 * Finds all instance of components in the rendered tree that are DOM 930 * components with the tag name matching `tagName`. 931 * @return {array} an array of all the matches. 932 */ 933 scryRenderedDOMComponentsWithTag: function (root, tagName) { 934 validateClassInstance(root, 'scryRenderedDOMComponentsWithTag'); 935 return ReactTestUtils.findAllInRenderedTree(root, function (inst) { 936 return ReactTestUtils.isDOMComponent(inst) && inst.tagName.toUpperCase() === tagName.toUpperCase(); 937 }); 938 }, 939 940 /** 941 * Like scryRenderedDOMComponentsWithTag but expects there to be one result, 942 * and returns that one result, or throws exception if there is any other 943 * number of matches besides one. 944 * @return {!ReactDOMComponent} The one match. 945 */ 946 findRenderedDOMComponentWithTag: function (root, tagName) { 947 validateClassInstance(root, 'findRenderedDOMComponentWithTag'); 948 var all = ReactTestUtils.scryRenderedDOMComponentsWithTag(root, tagName); 949 if (all.length !== 1) { 950 throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for tag:' + tagName); 951 } 952 return all[0]; 953 }, 954 955 /** 956 * Finds all instances of components with type equal to `componentType`. 957 * @return {array} an array of all the matches. 958 */ 959 scryRenderedComponentsWithType: function (root, componentType) { 960 validateClassInstance(root, 'scryRenderedComponentsWithType'); 961 return ReactTestUtils.findAllInRenderedTree(root, function (inst) { 962 return ReactTestUtils.isCompositeComponentWithType(inst, componentType); 963 }); 964 }, 965 966 /** 967 * Same as `scryRenderedComponentsWithType` but expects there to be one result 968 * and returns that one result, or throws exception if there is any other 969 * number of matches besides one. 970 * @return {!ReactComponent} The one match. 971 */ 972 findRenderedComponentWithType: function (root, componentType) { 973 validateClassInstance(root, 'findRenderedComponentWithType'); 974 var all = ReactTestUtils.scryRenderedComponentsWithType(root, componentType); 975 if (all.length !== 1) { 976 throw new Error('Did not find exactly one match (found: ' + all.length + ') ' + 'for componentType:' + componentType); 977 } 978 return all[0]; 979 }, 980 981 /** 982 * Pass a mocked component module to this method to augment it with 983 * useful methods that allow it to be used as a dummy React component. 984 * Instead of rendering as usual, the component will become a simple 985 * <div> containing any provided children. 986 * 987 * @param {object} module the mock function object exported from a 988 * module that defines the component to be mocked 989 * @param {?string} mockTagName optional dummy root tag name to return 990 * from render method (overrides 991 * module.mockTagName if provided) 992 * @return {object} the ReactTestUtils object (for chaining) 993 */ 994 mockComponent: function (module, mockTagName) { 995 mockTagName = mockTagName || module.mockTagName || 'div'; 996 997 module.prototype.render.mockImplementation(function () { 998 return React.createElement(mockTagName, null, this.props.children); 999 }); 1000 1001 return this; 1002 }, 1003 1004 nativeTouchData: function (x, y) { 1005 return { 1006 touches: [{ pageX: x, pageY: y }] 1007 }; 1008 }, 1009 1010 Simulate: null, 1011 SimulateNative: {}, 1012 1013 act: function (callback) { 1014 if (actContainerElement === null) { 1015 // warn if we can't actually create the stub element 1016 actContainerElement = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); 1017 } 1018 1019 var result = ReactDOM.unstable_batchedUpdates(callback); 1020 // note: keep these warning messages in sync with 1021 // createReactNoop.js and ReactTestRenderer.js 1022 ReactDOM.render(React.createElement('div', null), actContainerElement); 1023 // we want the user to not expect a return, 1024 // but we want to warn if they use it like they can await on it. 1025 return { 1026 then: function () { 1027 1028 } 1029 }; 1030 } 1031 }; 1032 1033 /** 1034 * Exports: 1035 * 1036 * - `ReactTestUtils.Simulate.click(Element)` 1037 * - `ReactTestUtils.Simulate.mouseMove(Element)` 1038 * - `ReactTestUtils.Simulate.change(Element)` 1039 * - ... (All keys from event plugin `eventTypes` objects) 1040 */ 1041 function makeSimulator(eventType) { 1042 return function (domNode, eventData) { 1043 !!React.isValidElement(domNode) ? reactProdInvariant('228') : void 0; 1044 !!ReactTestUtils.isCompositeComponent(domNode) ? reactProdInvariant('229') : void 0; 1045 1046 var dispatchConfig = eventNameDispatchConfigs[eventType]; 1047 1048 var fakeNativeEvent = new Event(); 1049 fakeNativeEvent.target = domNode; 1050 fakeNativeEvent.type = eventType.toLowerCase(); 1051 1052 // We don't use SyntheticEvent.getPooled in order to not have to worry about 1053 // properly destroying any properties assigned from `eventData` upon release 1054 var targetInst = getInstanceFromNode(domNode); 1055 var event = new SyntheticEvent(dispatchConfig, targetInst, fakeNativeEvent, domNode); 1056 1057 // Since we aren't using pooling, always persist the event. This will make 1058 // sure it's marked and won't warn when setting additional properties. 1059 event.persist(); 1060 _assign(event, eventData); 1061 1062 if (dispatchConfig.phasedRegistrationNames) { 1063 accumulateTwoPhaseDispatches(event); 1064 } else { 1065 accumulateDirectDispatches(event); 1066 } 1067 1068 ReactDOM.unstable_batchedUpdates(function () { 1069 // Normally extractEvent enqueues a state restore, but we'll just always 1070 // do that since we're by-passing it here. 1071 enqueueStateRestore(domNode); 1072 runEventsInBatch(event); 1073 }); 1074 restoreStateIfNeeded(); 1075 }; 1076 } 1077 1078 function buildSimulators() { 1079 ReactTestUtils.Simulate = {}; 1080 1081 var eventType = void 0; 1082 for (eventType in eventNameDispatchConfigs) { 1083 /** 1084 * @param {!Element|ReactDOMComponent} domComponentOrNode 1085 * @param {?object} eventData Fake event data to use in SyntheticEvent. 1086 */ 1087 ReactTestUtils.Simulate[eventType] = makeSimulator(eventType); 1088 } 1089 } 1090 1091 buildSimulators(); 1092 1093 /** 1094 * Exports: 1095 * 1096 * - `ReactTestUtils.SimulateNative.click(Element/ReactDOMComponent)` 1097 * - `ReactTestUtils.SimulateNative.mouseMove(Element/ReactDOMComponent)` 1098 * - `ReactTestUtils.SimulateNative.mouseIn/ReactDOMComponent)` 1099 * - `ReactTestUtils.SimulateNative.mouseOut(Element/ReactDOMComponent)` 1100 * - ... (All keys from `BrowserEventConstants.topLevelTypes`) 1101 * 1102 * Note: Top level event types are a subset of the entire set of handler types 1103 * (which include a broader set of "synthetic" events). For example, onDragDone 1104 * is a synthetic event. Except when testing an event plugin or React's event 1105 * handling code specifically, you probably want to use ReactTestUtils.Simulate 1106 * to dispatch synthetic events. 1107 */ 1108 1109 function makeNativeSimulator(eventType, topLevelType) { 1110 return function (domComponentOrNode, nativeEventData) { 1111 var fakeNativeEvent = new Event(eventType); 1112 _assign(fakeNativeEvent, nativeEventData); 1113 if (ReactTestUtils.isDOMComponent(domComponentOrNode)) { 1114 simulateNativeEventOnDOMComponent(topLevelType, domComponentOrNode, fakeNativeEvent); 1115 } else if (domComponentOrNode.tagName) { 1116 // Will allow on actual dom nodes. 1117 simulateNativeEventOnNode(topLevelType, domComponentOrNode, fakeNativeEvent); 1118 } 1119 }; 1120 } 1121 1122 [[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) { 1123 var topLevelType = _ref[0], 1124 eventType = _ref[1]; 1125 1126 /** 1127 * @param {!Element|ReactDOMComponent} domComponentOrNode 1128 * @param {?Event} nativeEventData Fake native event to use in SyntheticEvent. 1129 */ 1130 ReactTestUtils.SimulateNative[eventType] = makeNativeSimulator(eventType, topLevelType); 1131 }); 1132 1133 1134 1135 var ReactTestUtils$2 = ({ 1136 default: ReactTestUtils 1137 }); 1138 1139 var ReactTestUtils$3 = ( ReactTestUtils$2 && ReactTestUtils ) || ReactTestUtils$2; 1140 1141 // TODO: decide on the top-level export form. 1142 // This is hacky but makes it work with both Rollup and Jest. 1143 var testUtils = ReactTestUtils$3.default || ReactTestUtils$3; 1144 1145 export default testUtils;