From fc06c9ac048c8f411cabbb5b89f19e671e0f05b8 Mon Sep 17 00:00:00 2001 From: Mike Bland Date: Fri, 5 Jan 2024 12:17:51 -0500 Subject: [PATCH] Rethrow Jsdom import errors properly Based on advice from: - https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Error/Error#rethrowing_an_error_with_a_cause The Error object is now much more informative and useful, and the test performs specific assertions on each nested Error. --- lib/jsdom.js | 4 ++-- test/jsdom.test.js | 10 +++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/lib/jsdom.js b/lib/jsdom.js index cb5444b..6fff548 100644 --- a/lib/jsdom.js +++ b/lib/jsdom.js @@ -71,7 +71,7 @@ export default class JsdomPageOpener { try { await this.#importModules(window, document) } catch (err) { - throw new Error(`error importing modules from ${pagePath}: ${err}`) + throw new Error(`opening ${pagePath}`, { cause: err }) } return { window, document, close() { window.close() } } } @@ -159,6 +159,6 @@ function importModules(doc) { const modules = Array.from(doc.querySelectorAll('script[type="module"]')) return Promise.all(modules.filter(m => m.src).map(async m => { try { await import(m.src) } - catch (err) { throw new Error(`error importing ${m.src}: ${err}`) } + catch (err) { throw new Error(`importing ${m.src}`, { cause: err }) } })) } diff --git a/test/jsdom.test.js b/test/jsdom.test.js index 9c42691..1bfe8fd 100644 --- a/test/jsdom.test.js +++ b/test/jsdom.test.js @@ -17,8 +17,12 @@ describe.skipIf(globalThis.window !== undefined)('JsdomPageOpener', () => { const pagePath = './test-modules/error.html' const moduleUrl = pathToFileURL('./test-modules/error.js') - await expect(() => opener.open('unused', pagePath)).rejects - .toThrowError(`error importing modules from ${pagePath}: ` + - `Error: error importing ${moduleUrl.href}: Error: test error`) + const result = opener.open('unused', pagePath) + + await expect(result).rejects.toThrowError(`opening ${pagePath}`) + await result.catch(err => { + expect(err.cause.message).toBe(`importing ${moduleUrl.href}`) + expect(err.cause.cause.message).toBe('test error') + }) }) })