UNPKG

33.8 kBJavaScriptView Raw
1/** @license React v16.8.6
2 * react-test-renderer-shallow.development.js
3 *
4 * Copyright (c) Facebook, Inc. and its affiliates.
5 *
6 * This source code is licensed under the MIT license found in the
7 * LICENSE file in the root directory of this source tree.
8 */
9
10'use strict';
11
12
13
14if (process.env.NODE_ENV !== "production") {
15 (function() {
16'use strict';
17
18var _assign = require('object-assign');
19var React = require('react');
20var reactIs = require('react-is');
21var checkPropTypes = require('prop-types/checkPropTypes');
22
23/**
24 * Use invariant() to assert state which your program assumes to be true.
25 *
26 * Provide sprintf-style format (only %s is supported) and arguments
27 * to provide information about what broke and what you were
28 * expecting.
29 *
30 * The invariant message will be stripped in production, but the invariant
31 * will remain to ensure logic does not differ in production.
32 */
33
34var validateFormat = function () {};
35
36{
37 validateFormat = function (format) {
38 if (format === undefined) {
39 throw new Error('invariant requires an error message argument');
40 }
41 };
42}
43
44function invariant(condition, format, a, b, c, d, e, f) {
45 validateFormat(format);
46
47 if (!condition) {
48 var error = void 0;
49 if (format === undefined) {
50 error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
51 } else {
52 var args = [a, b, c, d, e, f];
53 var argIndex = 0;
54 error = new Error(format.replace(/%s/g, function () {
55 return args[argIndex++];
56 }));
57 error.name = 'Invariant Violation';
58 }
59
60 error.framesToPop = 1; // we don't care about invariant's own frame
61 throw error;
62 }
63}
64
65// Relying on the `invariant()` implementation lets us
66// preserve the format and params in the www builds.
67
68var BEFORE_SLASH_RE = /^(.*)[\\\/]/;
69
70var describeComponentFrame = function (name, source, ownerName) {
71 var sourceInfo = '';
72 if (source) {
73 var path = source.fileName;
74 var fileName = path.replace(BEFORE_SLASH_RE, '');
75 {
76 // In DEV, include code for a common special case:
77 // prefer "folder/index.js" instead of just "index.js".
78 if (/^index\./.test(fileName)) {
79 var match = path.match(BEFORE_SLASH_RE);
80 if (match) {
81 var pathBeforeSlash = match[1];
82 if (pathBeforeSlash) {
83 var folderName = pathBeforeSlash.replace(BEFORE_SLASH_RE, '');
84 fileName = folderName + '/' + fileName;
85 }
86 }
87 }
88 }
89 sourceInfo = ' (at ' + fileName + ':' + source.lineNumber + ')';
90 } else if (ownerName) {
91 sourceInfo = ' (created by ' + ownerName + ')';
92 }
93 return '\n in ' + (name || 'Unknown') + sourceInfo;
94};
95
96/**
97 * Similar to invariant but only logs a warning if the condition is not met.
98 * This can be used to log issues in development environments in critical
99 * paths. Removing the logging code for production environments will keep the
100 * same logic and follow the same code paths.
101 */
102
103var warningWithoutStack = function () {};
104
105{
106 warningWithoutStack = function (condition, format) {
107 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
108 args[_key - 2] = arguments[_key];
109 }
110
111 if (format === undefined) {
112 throw new Error('`warningWithoutStack(condition, format, ...args)` requires a warning ' + 'message argument');
113 }
114 if (args.length > 8) {
115 // Check before the condition to catch violations early.
116 throw new Error('warningWithoutStack() currently supports at most 8 arguments.');
117 }
118 if (condition) {
119 return;
120 }
121 if (typeof console !== 'undefined') {
122 var argsWithFormat = args.map(function (item) {
123 return '' + item;
124 });
125 argsWithFormat.unshift('Warning: ' + format);
126
127 // We intentionally don't use spread (or .apply) directly because it
128 // breaks IE9: https://github.com/facebook/react/issues/13610
129 Function.prototype.apply.call(console.error, console, argsWithFormat);
130 }
131 try {
132 // --- Welcome to debugging React ---
133 // This error was thrown as a convenience so that you can use this stack
134 // to find the callsite that caused this warning to fire.
135 var argIndex = 0;
136 var message = 'Warning: ' + format.replace(/%s/g, function () {
137 return args[argIndex++];
138 });
139 throw new Error(message);
140 } catch (x) {}
141 };
142}
143
144var warningWithoutStack$1 = warningWithoutStack;
145
146// The Symbol used to tag the ReactElement-like types. If there is no native Symbol
147// nor polyfill, then a plain number is used for performance.
148var hasSymbol = typeof Symbol === 'function' && Symbol.for;
149
150
151var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for('react.portal') : 0xeaca;
152var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for('react.fragment') : 0xeacb;
153var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for('react.strict_mode') : 0xeacc;
154var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for('react.profiler') : 0xead2;
155var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for('react.provider') : 0xeacd;
156var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for('react.context') : 0xeace;
157
158var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for('react.concurrent_mode') : 0xeacf;
159var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0;
160var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for('react.suspense') : 0xead1;
161var REACT_MEMO_TYPE = hasSymbol ? Symbol.for('react.memo') : 0xead3;
162var REACT_LAZY_TYPE = hasSymbol ? Symbol.for('react.lazy') : 0xead4;
163
164var Resolved = 1;
165
166
167function refineResolvedLazyComponent(lazyComponent) {
168 return lazyComponent._status === Resolved ? lazyComponent._result : null;
169}
170
171function getWrappedName(outerType, innerType, wrapperName) {
172 var functionName = innerType.displayName || innerType.name || '';
173 return outerType.displayName || (functionName !== '' ? wrapperName + '(' + functionName + ')' : wrapperName);
174}
175
176function getComponentName(type) {
177 if (type == null) {
178 // Host root, text node or just invalid type.
179 return null;
180 }
181 {
182 if (typeof type.tag === 'number') {
183 warningWithoutStack$1(false, 'Received an unexpected object in getComponentName(). ' + 'This is likely a bug in React. Please file an issue.');
184 }
185 }
186 if (typeof type === 'function') {
187 return type.displayName || type.name || null;
188 }
189 if (typeof type === 'string') {
190 return type;
191 }
192 switch (type) {
193 case REACT_CONCURRENT_MODE_TYPE:
194 return 'ConcurrentMode';
195 case REACT_FRAGMENT_TYPE:
196 return 'Fragment';
197 case REACT_PORTAL_TYPE:
198 return 'Portal';
199 case REACT_PROFILER_TYPE:
200 return 'Profiler';
201 case REACT_STRICT_MODE_TYPE:
202 return 'StrictMode';
203 case REACT_SUSPENSE_TYPE:
204 return 'Suspense';
205 }
206 if (typeof type === 'object') {
207 switch (type.$$typeof) {
208 case REACT_CONTEXT_TYPE:
209 return 'Context.Consumer';
210 case REACT_PROVIDER_TYPE:
211 return 'Context.Provider';
212 case REACT_FORWARD_REF_TYPE:
213 return getWrappedName(type, type.render, 'ForwardRef');
214 case REACT_MEMO_TYPE:
215 return getComponentName(type.type);
216 case REACT_LAZY_TYPE:
217 {
218 var thenable = type;
219 var resolvedThenable = refineResolvedLazyComponent(thenable);
220 if (resolvedThenable) {
221 return getComponentName(resolvedThenable);
222 }
223 }
224 }
225 }
226 return null;
227}
228
229/**
230 * inlined Object.is polyfill to avoid requiring consumers ship their own
231 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
232 */
233function is(x, y) {
234 return x === y && (x !== 0 || 1 / x === 1 / y) || x !== x && y !== y // eslint-disable-line no-self-compare
235 ;
236}
237
238var hasOwnProperty = Object.prototype.hasOwnProperty;
239
240/**
241 * Performs equality by iterating through keys on an object and returning false
242 * when any key has values which are not strictly equal between the arguments.
243 * Returns true when the values of all keys are strictly equal.
244 */
245function shallowEqual(objA, objB) {
246 if (is(objA, objB)) {
247 return true;
248 }
249
250 if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
251 return false;
252 }
253
254 var keysA = Object.keys(objA);
255 var keysB = Object.keys(objB);
256
257 if (keysA.length !== keysB.length) {
258 return false;
259 }
260
261 // Test for A's keys different from B.
262 for (var i = 0; i < keysA.length; i++) {
263 if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) {
264 return false;
265 }
266 }
267
268 return true;
269}
270
271var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
272
273// Prevent newer renderers from RTE when used with older react package versions.
274// Current owner and dispatcher used to share the same ref,
275// but PR #14548 split them out to better support the react-debug-tools package.
276if (!ReactSharedInternals.hasOwnProperty('ReactCurrentDispatcher')) {
277 ReactSharedInternals.ReactCurrentDispatcher = {
278 current: null
279 };
280}
281
282/**
283 * Similar to invariant but only logs a warning if the condition is not met.
284 * This can be used to log issues in development environments in critical
285 * paths. Removing the logging code for production environments will keep the
286 * same logic and follow the same code paths.
287 */
288
289var warning = warningWithoutStack$1;
290
291{
292 warning = function (condition, format) {
293 if (condition) {
294 return;
295 }
296 var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame;
297 var stack = ReactDebugCurrentFrame.getStackAddendum();
298 // eslint-disable-next-line react-internal/warning-and-invariant-args
299
300 for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
301 args[_key - 2] = arguments[_key];
302 }
303
304 warningWithoutStack$1.apply(undefined, [false, format + '%s'].concat(args, [stack]));
305 };
306}
307
308var warning$1 = warning;
309
310function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
311
312var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher;
313
314
315var RE_RENDER_LIMIT = 25;
316
317var emptyObject = {};
318{
319 Object.freeze(emptyObject);
320}
321
322// In DEV, this is the name of the currently executing primitive hook
323var currentHookNameInDev = void 0;
324
325function areHookInputsEqual(nextDeps, prevDeps) {
326 if (prevDeps === null) {
327 warning$1(false, '%s received a final argument during this render, but not during ' + 'the previous render. Even though the final argument is optional, ' + 'its type cannot change between renders.', currentHookNameInDev);
328 return false;
329 }
330
331 // Don't bother comparing lengths in prod because these arrays should be
332 // passed inline.
333 if (nextDeps.length !== prevDeps.length) {
334 warning$1(false, 'The final argument passed to %s changed size between renders. The ' + 'order and size of this array must remain constant.\n\n' + 'Previous: %s\n' + 'Incoming: %s', currentHookNameInDev, '[' + nextDeps.join(', ') + ']', '[' + prevDeps.join(', ') + ']');
335 }
336 for (var i = 0; i < prevDeps.length && i < nextDeps.length; i++) {
337 if (is(nextDeps[i], prevDeps[i])) {
338 continue;
339 }
340 return false;
341 }
342 return true;
343}
344
345var Updater = function () {
346 function Updater(renderer) {
347 _classCallCheck(this, Updater);
348
349 this._renderer = renderer;
350 this._callbacks = [];
351 }
352
353 Updater.prototype._enqueueCallback = function _enqueueCallback(callback, publicInstance) {
354 if (typeof callback === 'function' && publicInstance) {
355 this._callbacks.push({
356 callback: callback,
357 publicInstance: publicInstance
358 });
359 }
360 };
361
362 Updater.prototype._invokeCallbacks = function _invokeCallbacks() {
363 var callbacks = this._callbacks;
364 this._callbacks = [];
365
366 callbacks.forEach(function (_ref) {
367 var callback = _ref.callback,
368 publicInstance = _ref.publicInstance;
369
370 callback.call(publicInstance);
371 });
372 };
373
374 Updater.prototype.isMounted = function isMounted(publicInstance) {
375 return !!this._renderer._element;
376 };
377
378 Updater.prototype.enqueueForceUpdate = function enqueueForceUpdate(publicInstance, callback, callerName) {
379 this._enqueueCallback(callback, publicInstance);
380 this._renderer._forcedUpdate = true;
381 this._renderer.render(this._renderer._element, this._renderer._context);
382 };
383
384 Updater.prototype.enqueueReplaceState = function enqueueReplaceState(publicInstance, completeState, callback, callerName) {
385 this._enqueueCallback(callback, publicInstance);
386 this._renderer._newState = completeState;
387 this._renderer.render(this._renderer._element, this._renderer._context);
388 };
389
390 Updater.prototype.enqueueSetState = function enqueueSetState(publicInstance, partialState, callback, callerName) {
391 this._enqueueCallback(callback, publicInstance);
392 var currentState = this._renderer._newState || publicInstance.state;
393
394 if (typeof partialState === 'function') {
395 partialState = partialState.call(publicInstance, currentState, publicInstance.props);
396 }
397
398 // Null and undefined are treated as no-ops.
399 if (partialState === null || partialState === undefined) {
400 return;
401 }
402
403 this._renderer._newState = _assign({}, currentState, partialState);
404
405 this._renderer.render(this._renderer._element, this._renderer._context);
406 };
407
408 return Updater;
409}();
410
411function createHook() {
412 return {
413 memoizedState: null,
414 queue: null,
415 next: null
416 };
417}
418
419function basicStateReducer(state, action) {
420 return typeof action === 'function' ? action(state) : action;
421}
422
423var ReactShallowRenderer = function () {
424 function ReactShallowRenderer() {
425 _classCallCheck(this, ReactShallowRenderer);
426
427 this._reset();
428 }
429
430 ReactShallowRenderer.prototype._reset = function _reset() {
431 this._context = null;
432 this._element = null;
433 this._instance = null;
434 this._newState = null;
435 this._rendered = null;
436 this._rendering = false;
437 this._forcedUpdate = false;
438 this._updater = new Updater(this);
439 this._dispatcher = this._createDispatcher();
440 this._workInProgressHook = null;
441 this._firstWorkInProgressHook = null;
442 this._isReRender = false;
443 this._didScheduleRenderPhaseUpdate = false;
444 this._renderPhaseUpdates = null;
445 this._numberOfReRenders = 0;
446 };
447
448 ReactShallowRenderer.prototype._validateCurrentlyRenderingComponent = function _validateCurrentlyRenderingComponent() {
449 !(this._rendering && !this._instance) ? invariant(false, 'Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.') : void 0;
450 };
451
452 ReactShallowRenderer.prototype._createDispatcher = function _createDispatcher() {
453 var _this = this;
454
455 var useReducer = function (reducer, initialArg, init) {
456 _this._validateCurrentlyRenderingComponent();
457 _this._createWorkInProgressHook();
458 var workInProgressHook = _this._workInProgressHook;
459
460 if (_this._isReRender) {
461 // This is a re-render.
462 var _queue = workInProgressHook.queue;
463 var _dispatch = _queue.dispatch;
464 if (_this._numberOfReRenders > 0) {
465 // Apply the new render phase updates to the previous current hook.
466 if (_this._renderPhaseUpdates !== null) {
467 // Render phase updates are stored in a map of queue -> linked list
468 var firstRenderPhaseUpdate = _this._renderPhaseUpdates.get(_queue);
469 if (firstRenderPhaseUpdate !== undefined) {
470 _this._renderPhaseUpdates.delete(_queue);
471 var _newState = workInProgressHook.memoizedState;
472 var _update = firstRenderPhaseUpdate;
473 do {
474 var _action = _update.action;
475 _newState = reducer(_newState, _action);
476 _update = _update.next;
477 } while (_update !== null);
478 workInProgressHook.memoizedState = _newState;
479 return [_newState, _dispatch];
480 }
481 }
482 return [workInProgressHook.memoizedState, _dispatch];
483 }
484 // Process updates outside of render
485 var newState = workInProgressHook.memoizedState;
486 var update = _queue.first;
487 if (update !== null) {
488 do {
489 var _action2 = update.action;
490 newState = reducer(newState, _action2);
491 update = update.next;
492 } while (update !== null);
493 _queue.first = null;
494 workInProgressHook.memoizedState = newState;
495 }
496 return [newState, _dispatch];
497 } else {
498 var initialState = void 0;
499 if (reducer === basicStateReducer) {
500 // Special case for `useState`.
501 initialState = typeof initialArg === 'function' ? initialArg() : initialArg;
502 } else {
503 initialState = init !== undefined ? init(initialArg) : initialArg;
504 }
505 workInProgressHook.memoizedState = initialState;
506 var _queue2 = workInProgressHook.queue = {
507 first: null,
508 dispatch: null
509 };
510 var _dispatch2 = _queue2.dispatch = _this._dispatchAction.bind(_this, _queue2);
511 return [workInProgressHook.memoizedState, _dispatch2];
512 }
513 };
514
515 var useState = function (initialState) {
516 return useReducer(basicStateReducer,
517 // useReducer has a special case to support lazy useState initializers
518 initialState);
519 };
520
521 var useMemo = function (nextCreate, deps) {
522 _this._validateCurrentlyRenderingComponent();
523 _this._createWorkInProgressHook();
524
525 var nextDeps = deps !== undefined ? deps : null;
526
527 if (_this._workInProgressHook !== null && _this._workInProgressHook.memoizedState !== null) {
528 var prevState = _this._workInProgressHook.memoizedState;
529 var prevDeps = prevState[1];
530 if (nextDeps !== null) {
531 if (areHookInputsEqual(nextDeps, prevDeps)) {
532 return prevState[0];
533 }
534 }
535 }
536
537 var nextValue = nextCreate();
538 _this._workInProgressHook.memoizedState = [nextValue, nextDeps];
539 return nextValue;
540 };
541
542 var useRef = function (initialValue) {
543 _this._validateCurrentlyRenderingComponent();
544 _this._createWorkInProgressHook();
545 var previousRef = _this._workInProgressHook.memoizedState;
546 if (previousRef === null) {
547 var ref = { current: initialValue };
548 {
549 Object.seal(ref);
550 }
551 _this._workInProgressHook.memoizedState = ref;
552 return ref;
553 } else {
554 return previousRef;
555 }
556 };
557
558 var readContext = function (context, observedBits) {
559 return context._currentValue;
560 };
561
562 var noOp = function () {
563 _this._validateCurrentlyRenderingComponent();
564 };
565
566 var identity = function (fn) {
567 return fn;
568 };
569
570 return {
571 readContext: readContext,
572 useCallback: identity,
573 useContext: function (context) {
574 _this._validateCurrentlyRenderingComponent();
575 return readContext(context);
576 },
577 useDebugValue: noOp,
578 useEffect: noOp,
579 useImperativeHandle: noOp,
580 useLayoutEffect: noOp,
581 useMemo: useMemo,
582 useReducer: useReducer,
583 useRef: useRef,
584 useState: useState
585 };
586 };
587
588 ReactShallowRenderer.prototype._dispatchAction = function _dispatchAction(queue, action) {
589 !(this._numberOfReRenders < RE_RENDER_LIMIT) ? invariant(false, 'Too many re-renders. React limits the number of renders to prevent an infinite loop.') : void 0;
590
591 if (this._rendering) {
592 // This is a render phase update. Stash it in a lazily-created map of
593 // queue -> linked list of updates. After this render pass, we'll restart
594 // and apply the stashed updates on top of the work-in-progress hook.
595 this._didScheduleRenderPhaseUpdate = true;
596 var update = {
597 action: action,
598 next: null
599 };
600 var renderPhaseUpdates = this._renderPhaseUpdates;
601 if (renderPhaseUpdates === null) {
602 this._renderPhaseUpdates = renderPhaseUpdates = new Map();
603 }
604 var firstRenderPhaseUpdate = renderPhaseUpdates.get(queue);
605 if (firstRenderPhaseUpdate === undefined) {
606 renderPhaseUpdates.set(queue, update);
607 } else {
608 // Append the update to the end of the list.
609 var lastRenderPhaseUpdate = firstRenderPhaseUpdate;
610 while (lastRenderPhaseUpdate.next !== null) {
611 lastRenderPhaseUpdate = lastRenderPhaseUpdate.next;
612 }
613 lastRenderPhaseUpdate.next = update;
614 }
615 } else {
616 var _update2 = {
617 action: action,
618 next: null
619 };
620
621 // Append the update to the end of the list.
622 var last = queue.first;
623 if (last === null) {
624 queue.first = _update2;
625 } else {
626 while (last.next !== null) {
627 last = last.next;
628 }
629 last.next = _update2;
630 }
631
632 // Re-render now.
633 this.render(this._element, this._context);
634 }
635 };
636
637 ReactShallowRenderer.prototype._createWorkInProgressHook = function _createWorkInProgressHook() {
638 if (this._workInProgressHook === null) {
639 // This is the first hook in the list
640 if (this._firstWorkInProgressHook === null) {
641 this._isReRender = false;
642 this._firstWorkInProgressHook = this._workInProgressHook = createHook();
643 } else {
644 // There's already a work-in-progress. Reuse it.
645 this._isReRender = true;
646 this._workInProgressHook = this._firstWorkInProgressHook;
647 }
648 } else {
649 if (this._workInProgressHook.next === null) {
650 this._isReRender = false;
651 // Append to the end of the list
652 this._workInProgressHook = this._workInProgressHook.next = createHook();
653 } else {
654 // There's already a work-in-progress. Reuse it.
655 this._isReRender = true;
656 this._workInProgressHook = this._workInProgressHook.next;
657 }
658 }
659 return this._workInProgressHook;
660 };
661
662 ReactShallowRenderer.prototype._finishHooks = function _finishHooks(element, context) {
663 if (this._didScheduleRenderPhaseUpdate) {
664 // Updates were scheduled during the render phase. They are stored in
665 // the `renderPhaseUpdates` map. Call the component again, reusing the
666 // work-in-progress hooks and applying the additional updates on top. Keep
667 // restarting until no more updates are scheduled.
668 this._didScheduleRenderPhaseUpdate = false;
669 this._numberOfReRenders += 1;
670
671 // Start over from the beginning of the list
672 this._workInProgressHook = null;
673 this._rendering = false;
674 this.render(element, context);
675 } else {
676 this._workInProgressHook = null;
677 this._renderPhaseUpdates = null;
678 this._numberOfReRenders = 0;
679 }
680 };
681
682 ReactShallowRenderer.prototype.getMountedInstance = function getMountedInstance() {
683 return this._instance;
684 };
685
686 ReactShallowRenderer.prototype.getRenderOutput = function getRenderOutput() {
687 return this._rendered;
688 };
689
690 ReactShallowRenderer.prototype.render = function render(element) {
691 var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : emptyObject;
692
693 !React.isValidElement(element) ? invariant(false, 'ReactShallowRenderer render(): Invalid component element.%s', typeof element === 'function' ? ' Instead of passing a component class, make sure to instantiate ' + 'it by passing it to React.createElement.' : '') : void 0;
694 element = element;
695 // Show a special message for host elements since it's a common case.
696 !(typeof element.type !== 'string') ? invariant(false, 'ReactShallowRenderer render(): Shallow rendering works only with custom components, not primitives (%s). Instead of calling `.render(el)` and inspecting the rendered output, look at `el.props` directly instead.', element.type) : void 0;
697 !(reactIs.isForwardRef(element) || typeof element.type === 'function' || reactIs.isMemo(element.type)) ? invariant(false, 'ReactShallowRenderer render(): Shallow rendering works only with custom components, but the provided element type was `%s`.', Array.isArray(element.type) ? 'array' : element.type === null ? 'null' : typeof element.type) : void 0;
698
699 if (this._rendering) {
700 return;
701 }
702 if (this._element != null && this._element.type !== element.type) {
703 this._reset();
704 }
705
706 var elementType = reactIs.isMemo(element.type) ? element.type.type : element.type;
707 var previousElement = this._element;
708
709 this._rendering = true;
710 this._element = element;
711 this._context = getMaskedContext(elementType.contextTypes, context);
712
713 // Inner memo component props aren't currently validated in createElement.
714 if (reactIs.isMemo(element.type) && elementType.propTypes) {
715 currentlyValidatingElement = element;
716 checkPropTypes(elementType.propTypes, element.props, 'prop', getComponentName(elementType), getStackAddendum);
717 }
718
719 if (this._instance) {
720 this._updateClassComponent(elementType, element, this._context);
721 } else {
722 if (shouldConstruct(elementType)) {
723 this._instance = new elementType(element.props, this._context, this._updater);
724 if (typeof elementType.getDerivedStateFromProps === 'function') {
725 var partialState = elementType.getDerivedStateFromProps.call(null, element.props, this._instance.state);
726 if (partialState != null) {
727 this._instance.state = _assign({}, this._instance.state, partialState);
728 }
729 }
730
731 if (elementType.contextTypes) {
732 currentlyValidatingElement = element;
733 checkPropTypes(elementType.contextTypes, this._context, 'context', getName(elementType, this._instance), getStackAddendum);
734
735 currentlyValidatingElement = null;
736 }
737
738 this._mountClassComponent(elementType, element, this._context);
739 } else {
740 var shouldRender = true;
741 if (reactIs.isMemo(element.type) && previousElement !== null) {
742 // This is a Memo component that is being re-rendered.
743 var compare = element.type.compare || shallowEqual;
744 if (compare(previousElement.props, element.props)) {
745 shouldRender = false;
746 }
747 }
748 if (shouldRender) {
749 var prevDispatcher = ReactCurrentDispatcher.current;
750 ReactCurrentDispatcher.current = this._dispatcher;
751 try {
752 // elementType could still be a ForwardRef if it was
753 // nested inside Memo.
754 if (elementType.$$typeof === reactIs.ForwardRef) {
755 !(typeof elementType.render === 'function') ? invariant(false, 'forwardRef requires a render function but was given %s.', typeof elementType.render) : void 0;
756 this._rendered = elementType.render.call(undefined, element.props, element.ref);
757 } else {
758 this._rendered = elementType(element.props, this._context);
759 }
760 } finally {
761 ReactCurrentDispatcher.current = prevDispatcher;
762 }
763 this._finishHooks(element, context);
764 }
765 }
766 }
767
768 this._rendering = false;
769 this._updater._invokeCallbacks();
770
771 return this.getRenderOutput();
772 };
773
774 ReactShallowRenderer.prototype.unmount = function unmount() {
775 if (this._instance) {
776 if (typeof this._instance.componentWillUnmount === 'function') {
777 this._instance.componentWillUnmount();
778 }
779 }
780 this._reset();
781 };
782
783 ReactShallowRenderer.prototype._mountClassComponent = function _mountClassComponent(elementType, element, context) {
784 this._instance.context = context;
785 this._instance.props = element.props;
786 this._instance.state = this._instance.state || null;
787 this._instance.updater = this._updater;
788
789 if (typeof this._instance.UNSAFE_componentWillMount === 'function' || typeof this._instance.componentWillMount === 'function') {
790 var beforeState = this._newState;
791
792 // In order to support react-lifecycles-compat polyfilled components,
793 // Unsafe lifecycles should not be invoked for components using the new APIs.
794 if (typeof elementType.getDerivedStateFromProps !== 'function' && typeof this._instance.getSnapshotBeforeUpdate !== 'function') {
795 if (typeof this._instance.componentWillMount === 'function') {
796 this._instance.componentWillMount();
797 }
798 if (typeof this._instance.UNSAFE_componentWillMount === 'function') {
799 this._instance.UNSAFE_componentWillMount();
800 }
801 }
802
803 // setState may have been called during cWM
804 if (beforeState !== this._newState) {
805 this._instance.state = this._newState || emptyObject;
806 }
807 }
808
809 this._rendered = this._instance.render();
810 // Intentionally do not call componentDidMount()
811 // because DOM refs are not available.
812 };
813
814 ReactShallowRenderer.prototype._updateClassComponent = function _updateClassComponent(elementType, element, context) {
815 var props = element.props;
816
817
818 var oldState = this._instance.state || emptyObject;
819 var oldProps = this._instance.props;
820
821 if (oldProps !== props) {
822 // In order to support react-lifecycles-compat polyfilled components,
823 // Unsafe lifecycles should not be invoked for components using the new APIs.
824 if (typeof elementType.getDerivedStateFromProps !== 'function' && typeof this._instance.getSnapshotBeforeUpdate !== 'function') {
825 if (typeof this._instance.componentWillReceiveProps === 'function') {
826 this._instance.componentWillReceiveProps(props, context);
827 }
828 if (typeof this._instance.UNSAFE_componentWillReceiveProps === 'function') {
829 this._instance.UNSAFE_componentWillReceiveProps(props, context);
830 }
831 }
832 }
833
834 // Read state after cWRP in case it calls setState
835 var state = this._newState || oldState;
836 if (typeof elementType.getDerivedStateFromProps === 'function') {
837 var partialState = elementType.getDerivedStateFromProps.call(null, props, state);
838 if (partialState != null) {
839 state = _assign({}, state, partialState);
840 }
841 }
842
843 var shouldUpdate = true;
844 if (this._forcedUpdate) {
845 shouldUpdate = true;
846 this._forcedUpdate = false;
847 } else if (typeof this._instance.shouldComponentUpdate === 'function') {
848 shouldUpdate = !!this._instance.shouldComponentUpdate(props, state, context);
849 } else if (elementType.prototype && elementType.prototype.isPureReactComponent) {
850 shouldUpdate = !shallowEqual(oldProps, props) || !shallowEqual(oldState, state);
851 }
852
853 if (shouldUpdate) {
854 // In order to support react-lifecycles-compat polyfilled components,
855 // Unsafe lifecycles should not be invoked for components using the new APIs.
856 if (typeof elementType.getDerivedStateFromProps !== 'function' && typeof this._instance.getSnapshotBeforeUpdate !== 'function') {
857 if (typeof this._instance.componentWillUpdate === 'function') {
858 this._instance.componentWillUpdate(props, state, context);
859 }
860 if (typeof this._instance.UNSAFE_componentWillUpdate === 'function') {
861 this._instance.UNSAFE_componentWillUpdate(props, state, context);
862 }
863 }
864 }
865
866 this._instance.context = context;
867 this._instance.props = props;
868 this._instance.state = state;
869 this._newState = null;
870
871 if (shouldUpdate) {
872 this._rendered = this._instance.render();
873 }
874 // Intentionally do not call componentDidUpdate()
875 // because DOM refs are not available.
876 };
877
878 return ReactShallowRenderer;
879}();
880
881ReactShallowRenderer.createRenderer = function () {
882 return new ReactShallowRenderer();
883};
884
885var currentlyValidatingElement = null;
886
887function getDisplayName(element) {
888 if (element == null) {
889 return '#empty';
890 } else if (typeof element === 'string' || typeof element === 'number') {
891 return '#text';
892 } else if (typeof element.type === 'string') {
893 return element.type;
894 } else {
895 var elementType = reactIs.isMemo(element.type) ? element.type.type : element.type;
896 return elementType.displayName || elementType.name || 'Unknown';
897 }
898}
899
900function getStackAddendum() {
901 var stack = '';
902 if (currentlyValidatingElement) {
903 var name = getDisplayName(currentlyValidatingElement);
904 var owner = currentlyValidatingElement._owner;
905 stack += describeComponentFrame(name, currentlyValidatingElement._source, owner && getComponentName(owner.type));
906 }
907 return stack;
908}
909
910function getName(type, instance) {
911 var constructor = instance && instance.constructor;
912 return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null;
913}
914
915function shouldConstruct(Component) {
916 return !!(Component.prototype && Component.prototype.isReactComponent);
917}
918
919function getMaskedContext(contextTypes, unmaskedContext) {
920 if (!contextTypes || !unmaskedContext) {
921 return emptyObject;
922 }
923 var context = {};
924 for (var key in contextTypes) {
925 context[key] = unmaskedContext[key];
926 }
927 return context;
928}
929
930
931
932var ReactShallowRenderer$2 = Object.freeze({
933 default: ReactShallowRenderer
934});
935
936var ReactShallowRenderer$3 = ( ReactShallowRenderer$2 && ReactShallowRenderer ) || ReactShallowRenderer$2;
937
938// TODO: decide on the top-level export form.
939// This is hacky but makes it work with both Rollup and Jest.
940var shallow = ReactShallowRenderer$3.default || ReactShallowRenderer$3;
941
942module.exports = shallow;
943 })();
944}