o-error-util.test.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const { getFullInfo, getFullStack, hasCauseInstanceOf } = require('..')
  2. describe('OError.getFullInfo', () => {
  3. it('works on a normal error', () => {
  4. const err = new Error('foo')
  5. expect(getFullInfo(err)).to.deep.equal({ })
  6. })
  7. it('works on an error with .info', () => {
  8. const err = new Error('foo')
  9. err.info = { userId: 123 }
  10. expect(getFullInfo(err)).to.deep.equal({ userId: 123 })
  11. })
  12. it('merges info from a cause chain', () => {
  13. const err1 = new Error('foo')
  14. const err2 = new Error('bar')
  15. err1.cause = err2
  16. err2.info = { userId: 123 }
  17. expect(getFullInfo(err1)).to.deep.equal({ userId: 123 })
  18. })
  19. it('merges info from a cause chain with no info', () => {
  20. const err1 = new Error('foo')
  21. const err2 = new Error('bar')
  22. err1.cause = err2
  23. expect(getFullInfo(err1)).to.deep.equal({})
  24. })
  25. it('merges info from a cause chain with duplicate keys', () => {
  26. const err1 = new Error('foo')
  27. const err2 = new Error('bar')
  28. err1.cause = err2
  29. err1.info = { userId: 123 }
  30. err2.info = { userId: 456 }
  31. expect(getFullInfo(err1)).to.deep.equal({ userId: 123 })
  32. })
  33. it('works on an error with .info set to a string', () => {
  34. const err = new Error('foo')
  35. err.info = 'test'
  36. expect(getFullInfo(err)).to.deep.equal({})
  37. })
  38. })
  39. describe('OError.getFullStack', () => {
  40. it('works on a normal error', () => {
  41. const err = new Error('foo')
  42. const fullStack = getFullStack(err)
  43. expect(fullStack).to.match(/^Error: foo$/m)
  44. expect(fullStack).to.match(/^\s+at /m)
  45. })
  46. it('works on an error with a cause', () => {
  47. const err1 = new Error('foo')
  48. const err2 = new Error('bar')
  49. err1.cause = err2
  50. const fullStack = getFullStack(err1)
  51. expect(fullStack).to.match(/^Error: foo$/m)
  52. expect(fullStack).to.match(/^\s+at /m)
  53. expect(fullStack).to.match(/^caused by: Error: bar$/m)
  54. })
  55. })
  56. describe('OError.hasCauseInstanceOf', () => {
  57. it('works on a normal error', () => {
  58. const err = new Error('foo')
  59. expect(hasCauseInstanceOf(null, Error)).to.be.false
  60. expect(hasCauseInstanceOf(err, Error)).to.be.true
  61. expect(hasCauseInstanceOf(err, RangeError)).to.be.false
  62. })
  63. it('works on an error with a cause', () => {
  64. const err1 = new Error('foo')
  65. const err2 = new RangeError('bar')
  66. err1.cause = err2
  67. expect(hasCauseInstanceOf(err1, Error)).to.be.true
  68. expect(hasCauseInstanceOf(err1, RangeError)).to.be.true
  69. expect(hasCauseInstanceOf(err1, TypeError)).to.be.false
  70. })
  71. })