index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const { expect } = require('chai')
  2. const OError = require('../..')
  3. /**
  4. * @param {Error} e
  5. * @param {any} expected
  6. */
  7. exports.expectError = function OErrorExpectError(e, expected) {
  8. expect(
  9. e.name,
  10. "error should set the name property to the error's name"
  11. ).to.equal(expected.name)
  12. expect(
  13. e instanceof expected.klass,
  14. 'error should be an instance of the error type'
  15. ).to.be.true
  16. expect(
  17. e instanceof Error,
  18. 'error should be an instance of the built-in Error type'
  19. ).to.be.true
  20. expect(
  21. require('util').types.isNativeError(e),
  22. 'error should be recognised by util.types.isNativeError'
  23. ).to.be.true
  24. expect(
  25. e.toString(),
  26. 'toString should return the default error message formatting'
  27. ).to.equal(expected.message)
  28. expect(e.stack, 'error should have a stack trace').to.not.be.empty
  29. expect(
  30. /** @type {string} */ (e.stack).split('\n')[0],
  31. 'stack should start with the default error message formatting'
  32. ).to.match(new RegExp(`^${expected.name}:`))
  33. expect(
  34. /** @type {string} */ (e.stack).split('\n')[1],
  35. 'first stack frame should be the function where the error was thrown'
  36. ).to.match(expected.firstFrameRx)
  37. }
  38. /**
  39. * @param {Error} error
  40. * @param {String[]} expected
  41. */
  42. exports.expectFullStackWithoutStackFramesToEqual = function (error, expected) {
  43. const fullStack = OError.getFullStack(error)
  44. const fullStackWithoutFrames = fullStack
  45. .split('\n')
  46. .filter(line => !/^\s+at\s/.test(line))
  47. expect(
  48. fullStackWithoutFrames,
  49. 'full stack without frames should equal'
  50. ).to.deep.equal(expected)
  51. }