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