React Dom Test Utils - Development
React Dom Test Utils - Development
1
* [Link]
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var ReactSharedInternals =
React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; // Prevent newer
renderers from RTE when used with older react package versions.
// Current owner and dispatcher used to share the same ref,
// but PR #14548 split them out to better support the react-debug-tools package.
if () {
[Link] = {
current: null
};
}
if () {
[Link] = {
suspense: null
};
}
function warn(format) {
{
for (var _len = [Link], args = new Array(_len > 1 ? _len - 1 : 0),
_key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (!hasExistingStack) {
var ReactDebugCurrentFrame = [Link];
var stack = [Link]();
try {
// --- Welcome to debugging React ---
// This error was thrown as a convenience so that you can use this stack
// to find the callsite that caused this warning to fire.
var argIndex = 0;
var message = 'Warning: ' + [Link](/%s/g, function () {
return args[argIndex++];
});
throw new Error(message);
} catch (x) {}
}
}
/**
* `ReactInstanceMap` maintains a mapping from a public facing stateful
* instance (key) and the internal representation (value). This allows public
* methods to accept the user facing instance as an argument and map them back
* to internal methods.
*
* Note that this module is currently shared and assumed to be stateless.
* If this becomes an actual Map, that will break.
*/
function get(key) {
return key._reactInternalFiber;
}
var FunctionComponent = 0;
var ClassComponent = 1;
var HostRoot = 3; // Root of a host tree. Could be nested inside another node.
var HostComponent = 5;
var HostText = 6;
// Don't change these two values. They're used by React Dev Tools.
var NoEffect =
/* */
0;
var Placement =
/* */
2;
var Hydrating =
/* */
1024;
if (![Link]) {
// If there is no alternate, this might be a new tree that isn't inserted
// yet. If it is, then it will have a pending insertion effect on it.
var nextNode = node;
do {
node = nextNode;
nextNode = [Link];
} while (nextNode);
} else {
while ([Link]) {
node = [Link];
}
}
function assertIsMounted(fiber) {
if (!(getNearestMountedFiber(fiber) === fiber)) {
{
throw Error( "Unable to find node on an unmounted component." );
}
}
}
function findCurrentFiberUsingSlowPath(fiber) {
var alternate = [Link];
if (!alternate) {
// If there is no alternate, then we only need to check if it is mounted.
var nearestMounted = getNearestMountedFiber(fiber);
return fiber;
} // If we have two possible branches, we'll walk backwards up to the root
// to see what path the root points to. On the way we may hit one of the
// special cases and we'll deal with them.
var a = fiber;
var b = alternate;
while (true) {
var parentA = [Link];
while (child) {
if (child === a) {
// We've determined that A is the current branch.
assertIsMounted(parentA);
return fiber;
}
if (child === b) {
// We've determined that B is the current branch.
assertIsMounted(parentA);
return alternate;
}
child = [Link];
} // We should never have an alternate for any mounting node. So the only
// way this could possibly happen is if this was unmounted, if at all.
{
{
throw Error( "Unable to find node on an unmounted component." );
}
}
}
while (_child) {
if (_child === a) {
didFindChild = true;
a = parentA;
b = parentB;
break;
}
if (_child === b) {
didFindChild = true;
b = parentA;
a = parentB;
break;
}
_child = _child.sibling;
}
if (!didFindChild) {
// Search parent B's child set
_child = [Link];
while (_child) {
if (_child === a) {
didFindChild = true;
a = parentB;
b = parentA;
break;
}
if (_child === b) {
didFindChild = true;
b = parentB;
a = parentA;
break;
}
_child = _child.sibling;
}
if (!didFindChild) {
{
throw Error( "Child was not found in either parent set. This
indicates a bug in React related to the return pointer. Please file an issue." );
}
}
}
}
if ([Link] === a) {
// We've determined that A is the current branch.
return fiber;
} // Otherwise B has to be current branch.
return alternate;
}
var EventInterface = {
type: null,
target: null,
// currentTarget is set when dispatching; no use in copying it here
currentTarget: function () {
return null;
},
eventPhase: null,
bubbles: null,
cancelable: null,
timeStamp: function (event) {
return [Link] || [Link]();
},
defaultPrevented: null,
isTrusted: null
};
function functionThatReturnsTrue() {
return true;
}
function functionThatReturnsFalse() {
return false;
}
/**
* Synthetic events are dispatched by event plugins, typically in response to a
* top-level event delegation handler.
*
* These systems should generally use pooling to reduce the frequency of garbage
* collection. The system should check `isPersistent` to determine whether the
* event should be released into the pool after being dispatched. Users that
* need a persisted event should invoke `persist`.
*
* Synthetic events (and subclasses) implement the DOM Level 3 Events API by
* normalizing browser quirks. Subclasses do not necessarily have to implement a
* DOM interface; custom application-specific events can also subclass this.
*
* @param {object} dispatchConfig Configuration used to dispatch this event.
* @param {*} targetInst Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
* @param {DOMEventTarget} nativeEventTarget Target node.
*/
[Link] = dispatchConfig;
this._targetInst = targetInst;
[Link] = nativeEvent;
var Interface = [Link];
{
delete this[propName]; // this has a getter/setter for warnings
}
if (normalize) {
this[propName] = normalize(nativeEvent);
} else {
if (propName === 'target') {
[Link] = nativeEventTarget;
} else {
this[propName] = nativeEvent[propName];
}
}
}
if (defaultPrevented) {
[Link] = functionThatReturnsTrue;
} else {
[Link] = functionThatReturnsFalse;
}
[Link] = functionThatReturnsFalse;
return this;
}
_assign([Link], {
preventDefault: function () {
[Link] = true;
var event = [Link];
if (!event) {
return;
}
if ([Link]) {
[Link]();
} else if (typeof [Link] !== 'unknown') {
[Link] = false;
}
[Link] = functionThatReturnsTrue;
},
stopPropagation: function () {
var event = [Link];
if (!event) {
return;
}
if ([Link]) {
[Link]();
} else if (typeof [Link] !== 'unknown') {
// The ChangeEventPlugin registers a "propertychange" event for
// IE. This event does not support bubbling or cancelling, and
// any references to cancelBubble throw "Member not found". A
// typeof check of "unknown" circumvents this issue (and is also
// IE specific).
[Link] = true;
}
[Link] = functionThatReturnsTrue;
},
/**
* We release all dispatched `SyntheticEvent`s after each event loop, adding
* them back into the pool. This allows a way to hold onto a reference that
* won't be added back into the pool.
*/
persist: function () {
[Link] = functionThatReturnsTrue;
},
/**
* Checks if this event should be released back into the pool.
*
* @return {boolean} True if this should not be released, false otherwise.
*/
isPersistent: functionThatReturnsFalse,
/**
* `PooledClass` looks for `destructor` on each instance it releases.
*/
destructor: function () {
var Interface = [Link];
[Link] = null;
this._targetInst = null;
[Link] = null;
[Link] = functionThatReturnsFalse;
[Link] = functionThatReturnsFalse;
this._dispatchListeners = null;
this._dispatchInstances = null;
{
[Link](this, 'nativeEvent',
getPooledWarningPropertyDefinition('nativeEvent', null));
[Link](this, 'isDefaultPrevented',
getPooledWarningPropertyDefinition('isDefaultPrevented',
functionThatReturnsFalse));
[Link](this, 'isPropagationStopped',
getPooledWarningPropertyDefinition('isPropagationStopped',
functionThatReturnsFalse));
[Link](this, 'preventDefault',
getPooledWarningPropertyDefinition('preventDefault', function () {}));
[Link](this, 'stopPropagation',
getPooledWarningPropertyDefinition('stopPropagation', function () {}));
}
}
});
[Link] = EventInterface;
/**
* Helper to reduce boilerplate when creating subclasses.
*/
[Link] = [Link];
var prototype = new E();
function Class() {
return [Link](this, arguments);
}
_assign(prototype, [Link]);
[Link] = prototype;
[Link] = Class;
[Link] = _assign({}, [Link], Interface);
[Link] = [Link];
addEventPoolingTo(Class);
return Class;
};
addEventPoolingTo(SyntheticEvent);
/**
* Helper to nullify syntheticEvent instance properties when destructing
*
* @param {String} propName
* @param {?object} getVal
* @return {object} defineProperty object
*/
function getPooledWarningPropertyDefinition(propName, getVal) {
var isFunction = typeof getVal === 'function';
return {
configurable: true,
set: set,
get: get
};
function set(val) {
var action = isFunction ? 'setting the method' : 'setting the property';
warn(action, 'This is effectively a no-op');
return val;
}
function get() {
var action = isFunction ? 'accessing the method' : 'accessing the property';
var result = isFunction ? 'This is a no-op function' : 'This is set to null';
warn(action, result);
return getVal;
}
if ([Link]) {
var instance = [Link]();
[Link](instance, dispatchConfig, targetInst, nativeEvent,
nativeInst);
return instance;
}
function releasePooledEvent(event) {
var EventConstructor = this;
[Link]();
function addEventPoolingTo(EventConstructor) {
[Link] = [];
[Link] = getPooledEvent;
[Link] = releasePooledEvent;
}
/**
* HTML nodeType values that represent the type of the node
*/
var ELEMENT_NODE = 1;
var canUseDOM = !!(typeof window !== 'undefined' && typeof [Link] !==
'undefined' && typeof [Link] !== 'undefined');
/**
* Generate a mapping of standard vendor prefixes using the defined style
property and event name.
*
* @param {string} styleProp
* @param {string} eventName
* @returns {object}
*/
var vendorPrefixes = {
animationend: makePrefixMap('Animation', 'AnimationEnd'),
animationiteration: makePrefixMap('Animation', 'AnimationIteration'),
animationstart: makePrefixMap('Animation', 'AnimationStart'),
transitionend: makePrefixMap('Transition', 'TransitionEnd')
};
/**
* Event names that have already been detected and prefixed (if applicable).
*/
if (canUseDOM) {
style = [Link]('div').style; // On some platforms, in
particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are usable, and if not remove them from
the map.
if (!('AnimationEvent' in window)) {
delete [Link];
delete [Link];
delete [Link];
} // Same as above
if (!('TransitionEvent' in window)) {
delete [Link];
}
}
/**
* Attempts to determine the correct vendor prefixed event name.
*
* @param {string} eventName
* @returns {string}
*/
function getVendorPrefixedEventName(eventName) {
if (prefixedEventNames[eventName]) {
return prefixedEventNames[eventName];
} else if (!vendorPrefixes[eventName]) {
return eventName;
}
return eventName;
}
/**
* To identify top level events in ReactDOM, we use constants defined by this
* module. This is the only module that uses the unsafe* methods to express
* that the constants actually correspond to the browser event names. This lets
* us save some bundle size by avoiding a top level type -> event name map.
* The rest of ReactDOM code should import top level types from this file.
*/
var TOP_ABORT = unsafeCastStringToDOMTopLevelType('abort');
var TOP_ANIMATION_END =
unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationend'));
var TOP_ANIMATION_ITERATION =
unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationiteration'))
;
var TOP_ANIMATION_START =
unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('animationstart'));
var TOP_BLUR = unsafeCastStringToDOMTopLevelType('blur');
var TOP_CAN_PLAY = unsafeCastStringToDOMTopLevelType('canplay');
var TOP_CAN_PLAY_THROUGH = unsafeCastStringToDOMTopLevelType('canplaythrough');
var TOP_CANCEL = unsafeCastStringToDOMTopLevelType('cancel');
var TOP_CHANGE = unsafeCastStringToDOMTopLevelType('change');
var TOP_CLICK = unsafeCastStringToDOMTopLevelType('click');
var TOP_CLOSE = unsafeCastStringToDOMTopLevelType('close');
var TOP_COMPOSITION_END = unsafeCastStringToDOMTopLevelType('compositionend');
var TOP_COMPOSITION_START =
unsafeCastStringToDOMTopLevelType('compositionstart');
var TOP_COMPOSITION_UPDATE =
unsafeCastStringToDOMTopLevelType('compositionupdate');
var TOP_CONTEXT_MENU = unsafeCastStringToDOMTopLevelType('contextmenu');
var TOP_COPY = unsafeCastStringToDOMTopLevelType('copy');
var TOP_CUT = unsafeCastStringToDOMTopLevelType('cut');
var TOP_DOUBLE_CLICK = unsafeCastStringToDOMTopLevelType('dblclick');
var TOP_DRAG = unsafeCastStringToDOMTopLevelType('drag');
var TOP_DRAG_END = unsafeCastStringToDOMTopLevelType('dragend');
var TOP_DRAG_ENTER = unsafeCastStringToDOMTopLevelType('dragenter');
var TOP_DRAG_EXIT = unsafeCastStringToDOMTopLevelType('dragexit');
var TOP_DRAG_LEAVE = unsafeCastStringToDOMTopLevelType('dragleave');
var TOP_DRAG_OVER = unsafeCastStringToDOMTopLevelType('dragover');
var TOP_DRAG_START = unsafeCastStringToDOMTopLevelType('dragstart');
var TOP_DROP = unsafeCastStringToDOMTopLevelType('drop');
var TOP_DURATION_CHANGE = unsafeCastStringToDOMTopLevelType('durationchange');
var TOP_EMPTIED = unsafeCastStringToDOMTopLevelType('emptied');
var TOP_ENCRYPTED = unsafeCastStringToDOMTopLevelType('encrypted');
var TOP_ENDED = unsafeCastStringToDOMTopLevelType('ended');
var TOP_ERROR = unsafeCastStringToDOMTopLevelType('error');
var TOP_FOCUS = unsafeCastStringToDOMTopLevelType('focus');
var TOP_INPUT = unsafeCastStringToDOMTopLevelType('input');
var TOP_KEY_DOWN = unsafeCastStringToDOMTopLevelType('keydown');
var TOP_KEY_PRESS = unsafeCastStringToDOMTopLevelType('keypress');
var TOP_KEY_UP = unsafeCastStringToDOMTopLevelType('keyup');
var TOP_LOAD = unsafeCastStringToDOMTopLevelType('load');
var TOP_LOAD_START = unsafeCastStringToDOMTopLevelType('loadstart');
var TOP_LOADED_DATA = unsafeCastStringToDOMTopLevelType('loadeddata');
var TOP_LOADED_METADATA = unsafeCastStringToDOMTopLevelType('loadedmetadata');
var TOP_MOUSE_DOWN = unsafeCastStringToDOMTopLevelType('mousedown');
var TOP_MOUSE_MOVE = unsafeCastStringToDOMTopLevelType('mousemove');
var TOP_MOUSE_OUT = unsafeCastStringToDOMTopLevelType('mouseout');
var TOP_MOUSE_OVER = unsafeCastStringToDOMTopLevelType('mouseover');
var TOP_MOUSE_UP = unsafeCastStringToDOMTopLevelType('mouseup');
var TOP_PASTE = unsafeCastStringToDOMTopLevelType('paste');
var TOP_PAUSE = unsafeCastStringToDOMTopLevelType('pause');
var TOP_PLAY = unsafeCastStringToDOMTopLevelType('play');
var TOP_PLAYING = unsafeCastStringToDOMTopLevelType('playing');
var TOP_PROGRESS = unsafeCastStringToDOMTopLevelType('progress');
var TOP_RATE_CHANGE = unsafeCastStringToDOMTopLevelType('ratechange');
var TOP_SCROLL = unsafeCastStringToDOMTopLevelType('scroll');
var TOP_SEEKED = unsafeCastStringToDOMTopLevelType('seeked');
var TOP_SEEKING = unsafeCastStringToDOMTopLevelType('seeking');
var TOP_SELECTION_CHANGE = unsafeCastStringToDOMTopLevelType('selectionchange');
var TOP_STALLED = unsafeCastStringToDOMTopLevelType('stalled');
var TOP_SUSPEND = unsafeCastStringToDOMTopLevelType('suspend');
var TOP_TEXT_INPUT = unsafeCastStringToDOMTopLevelType('textInput');
var TOP_TIME_UPDATE = unsafeCastStringToDOMTopLevelType('timeupdate');
var TOP_TOGGLE = unsafeCastStringToDOMTopLevelType('toggle');
var TOP_TOUCH_CANCEL = unsafeCastStringToDOMTopLevelType('touchcancel');
var TOP_TOUCH_END = unsafeCastStringToDOMTopLevelType('touchend');
var TOP_TOUCH_MOVE = unsafeCastStringToDOMTopLevelType('touchmove');
var TOP_TOUCH_START = unsafeCastStringToDOMTopLevelType('touchstart');
var TOP_TRANSITION_END =
unsafeCastStringToDOMTopLevelType(getVendorPrefixedEventName('transitionend'));
var TOP_VOLUME_CHANGE = unsafeCastStringToDOMTopLevelType('volumechange');
var TOP_WAITING = unsafeCastStringToDOMTopLevelType('waiting');
var TOP_WHEEL = unsafeCastStringToDOMTopLevelType('wheel'); // List of events
that need to be individually attached to media elements.
var PLUGIN_EVENT_SYSTEM = 1;
enqueueTaskImpl = nodeRequire('timers').setImmediate;
} catch (_err) {
// we're in a browser
// we can't use regular timers because they may still be faked
// so we try MessageChannel+postMessage instead
enqueueTaskImpl = function (callback) {
{
if (didWarnAboutMessageChannel === false) {
didWarnAboutMessageChannel = true;
var _ReactDOM$__SECRET_IN =
ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events,
/* eslint-disable no-unused-vars */
getInstanceFromNode = _ReactDOM$__SECRET_IN[0],
getNodeFromInstance = _ReactDOM$__SECRET_IN[1],
getFiberCurrentPropsFromNode = _ReactDOM$__SECRET_IN[2],
injectEventPluginsByName = _ReactDOM$__SECRET_IN[3],
eventNameDispatchConfigs = _ReactDOM$__SECRET_IN[4],
accumulateTwoPhaseDispatches = _ReactDOM$__SECRET_IN[5],
accumulateDirectDispatches = _ReactDOM$__SECRET_IN[6],
enqueueStateRestore = _ReactDOM$__SECRET_IN[7],
restoreStateIfNeeded = _ReactDOM$__SECRET_IN[8],
dispatchEvent = _ReactDOM$__SECRET_IN[9],
runEventsInBatch = _ReactDOM$__SECRET_IN[10],
/* eslint-enable no-unused-vars */
flushPassiveEffects = _ReactDOM$__SECRET_IN[11],
IsThisRendererActing = _ReactDOM$__SECRET_IN[12];
var batchedUpdates = ReactDOM.unstable_batchedUpdates;
var IsSomeRendererActing = [Link]; // this
implementation should be exactly the same in
// [Link], [Link], [Link]
while (flushPassiveEffects()) {
didFlushWork = true;
}
return didFlushWork;
};
function flushWorkAndMicroTasks(onDone) {
try {
flushWork();
enqueueTask(function () {
if (flushWork()) {
flushWorkAndMicroTasks(onDone);
} else {
onDone();
}
});
} catch (err) {
onDone(err);
}
} // we track the 'depth' of the act() calls with this counter,
// so we can tell if any async act() calls try to run in parallel.
var actingUpdatesScopeDepth = 0;
function act(callback) {
function onDone() {
actingUpdatesScopeDepth--;
[Link] = previousIsSomeRendererActing;
[Link] = previousIsThisRendererActing;
{
if (actingUpdatesScopeDepth > previousActingUpdatesScopeDepth) {
// if it's _less than_ previousActingUpdatesScopeDepth, then we can
assume the 'other' one has warned
error('You seem to have overlapping act() calls, this is not supported. '
+ 'Be sure to await previous act() calls before making a new one. ');
}
}
}
var result;
try {
result = batchedUpdates(callback);
} catch (error) {
// on sync errors, we still want to 'cleanup' and decrement
actingUpdatesScopeDepth
onDone();
throw error;
}
if (result !== null && typeof result === 'object' && typeof [Link] ===
'function') {
// setup a boolean that gets set to true only
// once this act() call is await-ed
var called = false;
{
if (typeof Promise !== 'undefined') {
//eslint-disable-next-line no-undef
[Link]().then(function () {}).then(function () {
if (called === false) {
error('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 () => ...);');
}
});
}
} // in the async case, the returned thenable runs the callback, flushes
// effects and microtasks in a loop until flushPassiveEffects() === false,
// and cleans up
return {
then: function (resolve, reject) {
called = true;
[Link](function () {
if (actingUpdatesScopeDepth > 1 || isSchedulerMocked === true &&
previousIsSomeRendererActing === true) {
onDone();
resolve();
return;
} // we're about to exit the act() scope,
// now's the time to flush tasks/effects
flushWorkAndMicroTasks(function (err) {
onDone();
if (err) {
reject(err);
} else {
resolve();
}
});
}, function (err) {
onDone();
reject(err);
});
}
};
} else {
{
if (result !== undefined) {
error('The callback passed to act(...) function ' + 'must return
undefined, or a Promise. You returned %s', result);
}
} // flush effects until none remain, and cleanup
try {
if (actingUpdatesScopeDepth === 1 && (isSchedulerMocked === false ||
previousIsSomeRendererActing === false)) {
// we're about to exit the act() scope,
// now's the time to flush effects
flushWork();
}
onDone();
} catch (err) {
onDone();
throw err;
} // in the sync case, the returned thenable only warns *if* await-ed
return {
then: function (resolve) {
{
error('Do not await the result of calling act(...) with sync logic, it
is not a Promise.');
}
resolve();
}
};
}
}
var _ReactDOM$__SECRET_IN$1 =
ReactDOM.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.Events,
getInstanceFromNode$1 = _ReactDOM$__SECRET_IN$1[0],
/* eslint-disable no-unused-vars */
getNodeFromInstance$1 = _ReactDOM$__SECRET_IN$1[1],
getFiberCurrentPropsFromNode$1 = _ReactDOM$__SECRET_IN$1[2],
injectEventPluginsByName$1 = _ReactDOM$__SECRET_IN$1[3],
/* eslint-enable no-unused-vars */
eventNameDispatchConfigs$1 = _ReactDOM$__SECRET_IN$1[4],
accumulateTwoPhaseDispatches$1 = _ReactDOM$__SECRET_IN$1[5],
accumulateDirectDispatches$1 = _ReactDOM$__SECRET_IN$1[6],
enqueueStateRestore$1 = _ReactDOM$__SECRET_IN$1[7],
restoreStateIfNeeded$1 = _ReactDOM$__SECRET_IN$1[8],
dispatchEvent$1 = _ReactDOM$__SECRET_IN$1[9],
runEventsInBatch$1 = _ReactDOM$__SECRET_IN$1[10],
/* eslint-disable no-unused-vars */
flushPassiveEffects$1 = _ReactDOM$__SECRET_IN$1[11],
IsThisRendererActing$1
/* eslint-enable no-unused-vars */
= _ReactDOM$__SECRET_IN$1[12];
function Event(suffix) {}
/**
* Simulates a top level event being dispatched from a raw event that occurred
* on an `Element` node.
* @param {number} topLevelType A number from `TopLevelEventTypes`
* @param {!Element} node The dom to simulate an event occurring on.
* @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
*/
if (!currentParent) {
return [];
}
while (true) {
if ([Link] === HostComponent || [Link] === HostText || [Link] ===
ClassComponent || [Link] === FunctionComponent) {
var publicInst = [Link];
if (test(publicInst)) {
[Link](publicInst);
}
}
if ([Link]) {
[Link] = node;
node = [Link];
continue;
}
while (![Link]) {
if (![Link] || [Link] === currentParent) {
return ret;
}
node = [Link];
}
[Link] = [Link];
node = [Link];
}
}
if (get(inst)) {
// This is a public instance indeed.
return;
}
var received;
var stringified = '' + inst;
if ([Link](inst)) {
received = 'an array';
} else if (inst && [Link] === ELEMENT_NODE && [Link]) {
received = 'a DOM node';
} else if (stringified === '[object Object]') {
received = 'object with keys {' + [Link](inst).join(', ') + '}';
} else {
received = stringified;
}
{
{
throw Error( methodName + "(...): the first argument must be a React class
instance. Instead received: " + received + "." );
}
}
}
/**
* Utilities for making it easy to test React components.
*
* See [Link]
*
* Todo: Support the entire [Link] query syntax. For now, these simple
* utilities will suffice for testing purposes.
* @lends ReactTestUtils
*/
var ReactTestUtils = {
renderIntoDocument: function (element) {
var div = [Link]('div'); // None of our tests actually
require attaching the container to the
// DOM, and doing so creates a mess that we rely on test isolation to
// clean up, so we're going to stop honoring the name of this method
// (and probably rename it eventually) if no problems arise.
// [Link](div);
return inst != null && typeof [Link] === 'function' && typeof
[Link] === 'function';
},
isCompositeComponentWithType: function (inst, type) {
if () {
return false;
}
if (!inst) {
return [];
}
if () {
if (!(classNames !== undefined)) {
{
throw Error( "[Link] expects
a className as a second argument." );
}
}
classNames = [Link](/\s+/);
}
return false;
});
},
/**
* Like scryRenderedDOMComponentsWithClass but expects there to be one result,
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactDOMComponent} The one match.
*/
findRenderedDOMComponentWithClass: function (root, className) {
validateClassInstance(root, 'findRenderedDOMComponentWithClass');
var all = [Link](root, className);
if ([Link] !== 1) {
throw new Error('Did not find exactly one match (found: ' + [Link] + ')
' + 'for class:' + className);
}
return all[0];
},
/**
* Finds all instance of components in the rendered tree that are DOM
* components with the tag name matching `tagName`.
* @return {array} an array of all the matches.
*/
scryRenderedDOMComponentsWithTag: function (root, tagName) {
validateClassInstance(root, 'scryRenderedDOMComponentsWithTag');
return [Link](root, function (inst) {
return [Link](inst) && [Link]()
=== [Link]();
});
},
/**
* Like scryRenderedDOMComponentsWithTag but expects there to be one result,
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactDOMComponent} The one match.
*/
findRenderedDOMComponentWithTag: function (root, tagName) {
validateClassInstance(root, 'findRenderedDOMComponentWithTag');
var all = [Link](root, tagName);
if ([Link] !== 1) {
throw new Error('Did not find exactly one match (found: ' + [Link] + ')
' + 'for tag:' + tagName);
}
return all[0];
},
/**
* Finds all instances of components with type equal to `componentType`.
* @return {array} an array of all the matches.
*/
scryRenderedComponentsWithType: function (root, componentType) {
validateClassInstance(root, 'scryRenderedComponentsWithType');
return [Link](root, function (inst) {
return [Link](inst, componentType);
});
},
/**
* Same as `scryRenderedComponentsWithType` but expects there to be one result
* and returns that one result, or throws exception if there is any other
* number of matches besides one.
* @return {!ReactComponent} The one match.
*/
findRenderedComponentWithType: function (root, componentType) {
validateClassInstance(root, 'findRenderedComponentWithType');
var all = [Link](root, componentType);
if ([Link] !== 1) {
throw new Error('Did not find exactly one match (found: ' + [Link] + ')
' + 'for componentType:' + componentType);
}
return all[0];
},
/**
* Pass a mocked component module to this method to augment it with
* useful methods that allow it to be used as a dummy React component.
* Instead of rendering as usual, the component will become a simple
* <div> containing any provided children.
*
* @param {object} module the mock function object exported from a
* module that defines the component to be mocked
* @param {?string} mockTagName optional dummy root tag name to return
* from render method (overrides
* [Link] if provided)
* @return {object} the ReactTestUtils object (for chaining)
*/
mockComponent: function (module, mockTagName) {
{
if (!hasWarnedAboutDeprecatedMockComponent) {
hasWarnedAboutDeprecatedMockComponent = true;
function makeSimulator(eventType) {
return function (domNode, eventData) {
if (!) {
{
throw Error( "[Link] 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 [Link] will not work if you are using
shallow rendering." );
}
}
if (!) {
{
throw Error( "[Link] 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." );
}
}
[Link]();
_assign(event, eventData);
if ([Link]) {
accumulateTwoPhaseDispatches$1(event);
} else {
accumulateDirectDispatches$1(event);
}
ReactDOM.unstable_batchedUpdates(function () {
// Normally extractEvent enqueues a state restore, but we'll just always
// do that since we're by-passing it here.
enqueueStateRestore$1(domNode);
runEventsInBatch$1(event);
});
restoreStateIfNeeded$1();
};
}
function buildSimulators() {
[Link] = {};
var eventType;
buildSimulators();
/**
* Exports:
*
* - `[Link](Element/ReactDOMComponent)`
* - `[Link](Element/ReactDOMComponent)`
* - `[Link]/ReactDOMComponent)`
* - `[Link](Element/ReactDOMComponent)`
* - ... (All keys from `[Link]`)
*
* Note: Top level event types are a subset of the entire set of handler types
* (which include a broader set of "synthetic" events). For example, onDragDone
* is a synthetic event. Except when testing an event plugin or React's event
* handling code specifically, you probably want to use [Link]
* to dispatch synthetic events.
*/
_assign(fakeNativeEvent, nativeEventData);
if ([Link](domComponentOrNode)) {
simulateNativeEventOnDOMComponent(topLevelType, domComponentOrNode,
fakeNativeEvent);
} else if ([Link]) {
// Will allow on actual dom nodes.
simulateNativeEventOnNode(topLevelType, domComponentOrNode,
fakeNativeEvent);
}
};
}
/**
* @param {!Element|ReactDOMComponent} domComponentOrNode
* @param {?Event} nativeEventData Fake native event to use in SyntheticEvent.
*/
[Link][eventType] = makeNativeSimulator(eventType,
topLevelType);
});
return testUtils;
})));