strict-match-error.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. export function strictlyThrows(t, fn, pattern) {
  2. const error = catchErrorOrNull(fn);
  3. t.currentAssert = strictlyThrows;
  4. if (error === null) {
  5. t.fail(`expected to throw`);
  6. return;
  7. }
  8. const nameAndMessage = `${pattern.constructor.name} ${pattern.message}`;
  9. t.match(
  10. prepareErrorForMatch(error),
  11. prepareErrorForMatch(pattern),
  12. (pattern instanceof AggregateError
  13. ? `expected to throw: ${nameAndMessage} (${pattern.errors.length} error(s))`
  14. : `expected to throw: ${nameAndMessage}`));
  15. }
  16. function prepareErrorForMatch(error) {
  17. if (error instanceof RegExp) {
  18. return {
  19. message: error,
  20. };
  21. }
  22. if (!(error instanceof Error)) {
  23. return error;
  24. }
  25. const matchable = {
  26. name: error.constructor.name,
  27. message: error.message,
  28. };
  29. if (error instanceof AggregateError) {
  30. matchable.errors = error.errors.map(prepareErrorForMatch);
  31. }
  32. return matchable;
  33. }
  34. function catchErrorOrNull(fn) {
  35. try {
  36. fn();
  37. return null;
  38. } catch (error) {
  39. return error;
  40. }
  41. }