convertDescriptorToString.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = convertDescriptorToString;
  6. /**
  7. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  8. *
  9. * This source code is licensed under the MIT license found in the
  10. * LICENSE file in the root directory of this source tree.
  11. */
  12. /* eslint-disable local/ban-types-eventually */
  13. // See: https://github.com/facebook/jest/pull/5154
  14. function convertDescriptorToString(descriptor) {
  15. if (
  16. typeof descriptor === 'string' ||
  17. typeof descriptor === 'number' ||
  18. descriptor === undefined
  19. ) {
  20. return descriptor;
  21. }
  22. if (typeof descriptor !== 'function') {
  23. throw new Error('describe expects a class, function, number, or string.');
  24. }
  25. if (descriptor.name !== undefined) {
  26. return descriptor.name;
  27. } // Fallback for old browsers, pardon Flow
  28. const stringified = descriptor.toString();
  29. const typeDescriptorMatch = stringified.match(/class|function/);
  30. const indexOfNameSpace = // @ts-expect-error: typeDescriptorMatch exists
  31. typeDescriptorMatch.index + typeDescriptorMatch[0].length;
  32. const indexOfNameAfterSpace = stringified.search(/\(|\{/);
  33. const name = stringified.substring(indexOfNameSpace, indexOfNameAfterSpace);
  34. return name.trim();
  35. }