From f43813b35caf04670afdf450f354d1c0376715f3 Mon Sep 17 00:00:00 2001 From: Eric Arellano <14852634+Eric-Arellano@users.noreply.github.com> Date: Thu, 17 Oct 2024 11:27:53 -0400 Subject: [PATCH] Fix external link checker exception handling --- scripts/js/lib/links/ExternalLink.test.ts | 33 +++++++++++++++++------ scripts/js/lib/links/ExternalLink.ts | 4 +-- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/scripts/js/lib/links/ExternalLink.test.ts b/scripts/js/lib/links/ExternalLink.test.ts index 47805a79bc7..dfc52ca8ec5 100644 --- a/scripts/js/lib/links/ExternalLink.test.ts +++ b/scripts/js/lib/links/ExternalLink.test.ts @@ -20,21 +20,38 @@ test("ExternalLink constructor ignores anchors", () => { }); test.describe("ExternalLink.check()", () => { + let originalFetch: typeof global.fetch; + + test.beforeEach(() => { + originalFetch = global.fetch; + }); + + test.afterEach(() => { + global.fetch = originalFetch; + }); + test("valid link", async () => { - let link = new ExternalLink("https://github.com/Qiskit", [ - "/testorigin.mdx", - ]); + global.fetch = () => Promise.resolve(new Response()); + let link = new ExternalLink("https://good-link.com", ["/testorigin.mdx"]); const result = await link.check(); expect(result).toBeUndefined(); }); - test("Validate existing external links", async () => { - let link = new ExternalLink("https://ibm.com/FakePageDoesNotExist", [ - "/testorigin.mdx", - ]); + test("invalid link", async () => { + global.fetch = () => Promise.resolve(new Response("", { status: 404 })); + let link = new ExternalLink("https://bad-link.com", ["/testorigin.mdx"]); + const result = await link.check(); + expect(result).toEqual( + "❌ Could not find link 'https://bad-link.com'. Appears in:\n /testorigin.mdx", + ); + }); + + test("exception handling", async () => { + global.fetch = () => Promise.reject(new Error("some issue")); + let link = new ExternalLink("https://bad-link.com", ["/testorigin.mdx"]); const result = await link.check(); expect(result).toEqual( - "❌ Could not find link 'https://ibm.com/FakePageDoesNotExist'. Appears in:\n /testorigin.mdx", + "❌ Failed to fetch 'https://bad-link.com': some issue. Appears in:\n /testorigin.mdx", ); }); }); diff --git a/scripts/js/lib/links/ExternalLink.ts b/scripts/js/lib/links/ExternalLink.ts index 6074b477fa7..00bcec72e54 100644 --- a/scripts/js/lib/links/ExternalLink.ts +++ b/scripts/js/lib/links/ExternalLink.ts @@ -43,8 +43,8 @@ export class ExternalLink { if (response.status >= 300) { error = `Could not find link '${this.value}'`; } - } catch (error) { - error = `Failed to fetch '${this.value}': ${(error as Error).message}`; + } catch (err) { + error = `Failed to fetch '${this.value}': ${(err as Error).message}`; } if (!error) {