UNPKG

1.79 kBJavaScriptView Raw
1/**
2 * Copyright (c) Facebook, Inc. and its affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @format
8 */
9
10'use strict';
11
12module.exports = (moduleName, instanceMethods) => {
13 const RealComponent = jest.requireActual(moduleName);
14 const React = require('react');
15
16 const SuperClass =
17 typeof RealComponent === 'function' ? RealComponent : React.Component;
18
19 const Component = class extends SuperClass {
20 static displayName = 'Component';
21
22 render() {
23 const name =
24 RealComponent.displayName ||
25 RealComponent.name ||
26 (RealComponent.render // handle React.forwardRef
27 ? RealComponent.render.displayName || RealComponent.render.name
28 : 'Unknown');
29
30 const props = Object.assign({}, RealComponent.defaultProps);
31
32 if (this.props) {
33 Object.keys(this.props).forEach(prop => {
34 // We can't just assign props on top of defaultProps
35 // because React treats undefined as special and different from null.
36 // If a prop is specified but set to undefined it is ignored and the
37 // default prop is used instead. If it is set to null, then the
38 // null value overwrites the default value.
39 if (this.props[prop] !== undefined) {
40 props[prop] = this.props[prop];
41 }
42 });
43 }
44
45 return React.createElement(
46 name.replace(/^(RCT|RK)/, ''),
47 props,
48 this.props.children,
49 );
50 }
51 };
52
53 Object.keys(RealComponent).forEach(classStatic => {
54 Component[classStatic] = RealComponent[classStatic];
55 });
56
57 if (instanceMethods != null) {
58 Object.assign(Component.prototype, instanceMethods);
59 }
60
61 return Component;
62};