expectationResultFactory.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', {
  3. value: true
  4. });
  5. exports.default = expectationResultFactory;
  6. var _prettyFormat = require('pretty-format');
  7. /**
  8. * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
  9. *
  10. * This source code is licensed under the MIT license found in the
  11. * LICENSE file in the root directory of this source tree.
  12. */
  13. function messageFormatter({error, message, passed}) {
  14. if (passed) {
  15. return 'Passed.';
  16. }
  17. if (message) {
  18. return message;
  19. }
  20. if (typeof error === 'string') {
  21. return error;
  22. }
  23. if (
  24. // duck-type Error, see #2549
  25. error &&
  26. typeof error === 'object' &&
  27. typeof error.message === 'string' &&
  28. typeof error.name === 'string'
  29. ) {
  30. if (error.message === '') {
  31. return error.name;
  32. }
  33. return `${error.name}: ${error.message}`;
  34. }
  35. return `thrown: ${(0, _prettyFormat.format)(error, {
  36. maxDepth: 3
  37. })}`;
  38. }
  39. function stackFormatter(options, initError, errorMessage) {
  40. if (options.passed) {
  41. return '';
  42. }
  43. if (options.error) {
  44. if (typeof options.error.stack === 'string') {
  45. return options.error.stack;
  46. }
  47. if (options.error === errorMessage) {
  48. return errorMessage;
  49. }
  50. }
  51. if (initError) {
  52. return errorMessage.trimRight() + '\n\n' + initError.stack;
  53. }
  54. return new Error(errorMessage).stack;
  55. }
  56. function expectationResultFactory(options, initError) {
  57. const message = messageFormatter(options);
  58. const stack = stackFormatter(options, initError, message);
  59. if (options.passed) {
  60. return {
  61. error: options.error,
  62. matcherName: options.matcherName,
  63. message,
  64. passed: options.passed,
  65. stack
  66. };
  67. }
  68. return {
  69. actual: options.actual,
  70. error: options.error,
  71. expected: options.expected,
  72. matcherName: options.matcherName,
  73. message,
  74. passed: options.passed,
  75. stack
  76. };
  77. }