assertion-error.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. var util = require('./util');
  2. /**
  3. * should AssertionError
  4. * @param {Object} options
  5. * @constructor
  6. * @memberOf should
  7. * @static
  8. */
  9. var AssertionError = function AssertionError(options) {
  10. util.merge(this, options);
  11. if(!options.message) {
  12. Object.defineProperty(this, 'message', {
  13. get: function() {
  14. if(!this._message) {
  15. this._message = this.generateMessage();
  16. this.generatedMessage = true;
  17. }
  18. return this._message;
  19. },
  20. configurable: true,
  21. enumerable: false
  22. }
  23. );
  24. }
  25. if(Error.captureStackTrace) {
  26. Error.captureStackTrace(this, this.stackStartFunction);
  27. } else {
  28. // non v8 browsers so we can have a stacktrace
  29. var err = new Error();
  30. if(err.stack) {
  31. var out = err.stack;
  32. if(this.stackStartFunction) {
  33. // try to strip useless frames
  34. var fn_name = util.functionName(this.stackStartFunction);
  35. var idx = out.indexOf('\n' + fn_name);
  36. if(idx >= 0) {
  37. // once we have located the function frame
  38. // we need to strip out everything before it (and its line)
  39. var next_line = out.indexOf('\n', idx + 1);
  40. out = out.substring(next_line + 1);
  41. }
  42. }
  43. this.stack = out;
  44. }
  45. }
  46. };
  47. var indent = ' ';
  48. function prependIndent(line) {
  49. return indent + line;
  50. }
  51. function indentLines(text) {
  52. return text.split('\n').map(prependIndent).join('\n');
  53. }
  54. // assert.AssertionError instanceof Error
  55. AssertionError.prototype = Object.create(Error.prototype, {
  56. name: {
  57. value: 'AssertionError'
  58. },
  59. generateMessage: {
  60. value: function() {
  61. if(!this.operator && this.previous) {
  62. return this.previous.message;
  63. }
  64. var actual = util.format(this.actual);
  65. var expected = 'expected' in this ? ' ' + util.format(this.expected) : '';
  66. var details = 'details' in this && this.details ? ' (' + this.details + ')' : '';
  67. var previous = this.previous ? '\n' + indentLines(this.previous.message) : '';
  68. return 'expected ' + actual + (this.negate ? ' not ' : ' ') + this.operator + expected + details + previous;
  69. }
  70. }
  71. });
  72. module.exports = AssertionError;