mockComponent.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. 'use strict';
  10. module.exports = (moduleName, instanceMethods) => {
  11. const RealComponent = jest.requireActual(moduleName);
  12. const React = require('react');
  13. const SuperClass =
  14. typeof RealComponent === 'function' ? RealComponent : React.Component;
  15. const Component = class extends SuperClass {
  16. static displayName = 'Component';
  17. render() {
  18. const name =
  19. RealComponent.displayName ||
  20. RealComponent.name ||
  21. (RealComponent.render // handle React.forwardRef
  22. ? RealComponent.render.displayName || RealComponent.render.name
  23. : 'Unknown');
  24. const props = Object.assign({}, RealComponent.defaultProps);
  25. if (this.props) {
  26. Object.keys(this.props).forEach(prop => {
  27. // We can't just assign props on top of defaultProps
  28. // because React treats undefined as special and different from null.
  29. // If a prop is specified but set to undefined it is ignored and the
  30. // default prop is used instead. If it is set to null, then the
  31. // null value overwrites the default value.
  32. if (this.props[prop] !== undefined) {
  33. props[prop] = this.props[prop];
  34. }
  35. });
  36. }
  37. return React.createElement(
  38. name.replace(/^(RCT|RK)/, ''),
  39. props,
  40. this.props.children,
  41. );
  42. }
  43. };
  44. Object.keys(RealComponent).forEach(classStatic => {
  45. Component[classStatic] = RealComponent[classStatic];
  46. });
  47. if (instanceMethods != null) {
  48. Object.assign(Component.prototype, instanceMethods);
  49. }
  50. return Component;
  51. };