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