diff options
author | (quasar) nebula <qznebula@protonmail.com> | 2023-04-09 19:48:59 -0300 |
---|---|---|
committer | (quasar) nebula <qznebula@protonmail.com> | 2023-04-09 20:38:22 -0300 |
commit | 36ca344e24bbca16426348c23ba7894f671e18c9 (patch) | |
tree | 8478425b6eb6cf0c7761185e369ac5e86f39a9ad /test/lib | |
parent | 7f32560a93500777a877fd8f30a21c994662ae65 (diff) |
test: html.template & Template descriptor errors
Diffstat (limited to 'test/lib')
-rw-r--r-- | test/lib/strict-match-error.js | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/test/lib/strict-match-error.js b/test/lib/strict-match-error.js new file mode 100644 index 00000000..e3b36e93 --- /dev/null +++ b/test/lib/strict-match-error.js @@ -0,0 +1,50 @@ +export function strictlyThrows(t, fn, pattern) { + const error = catchErrorOrNull(fn); + + t.currentAssert = strictlyThrows; + + if (error === null) { + t.fail(`expected to throw`); + return; + } + + const nameAndMessage = `${pattern.constructor.name} ${pattern.message}`; + t.match( + prepareErrorForMatch(error), + prepareErrorForMatch(pattern), + (pattern instanceof AggregateError + ? `expected to throw: ${nameAndMessage} (${pattern.errors.length} error(s))` + : `expected to throw: ${nameAndMessage}`)); +} + +function prepareErrorForMatch(error) { + if (error instanceof RegExp) { + return { + message: error, + }; + } + + if (!(error instanceof Error)) { + return error; + } + + const matchable = { + name: error.constructor.name, + message: error.message, + }; + + if (error instanceof AggregateError) { + matchable.errors = error.errors.map(prepareErrorForMatch); + } + + return matchable; +} + +function catchErrorOrNull(fn) { + try { + fn(); + return null; + } catch (error) { + return error; + } +} |