UNPKG

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