Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

loadScript rejects with an Error #391

Merged
merged 4 commits into from
Feb 1, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/thirty-pianos-occur.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@guardian/libs': major
---

loadScript rejects with an Error
8 changes: 7 additions & 1 deletion libs/@guardian/libs/src/loadScript/loadScript.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ describe('loadScript', () => {
});

it('rejects if the script fails to load', async () => {
await expect(loadScript(badURL)).rejects.toMatch(badURL);
expect.assertions(2);
try {
await loadScript(badURL);
} catch (error) {
expect(error instanceof Error).toEqual(true);
expect((error as Error).message).toEqual('Error loading script: bad-url');
}
arelra marked this conversation as resolved.
Show resolved Hide resolved
});
});
12 changes: 4 additions & 8 deletions libs/@guardian/libs/src/loadScript/loadScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,26 +35,22 @@ export const loadScript = (
) => {
if (error) {
reject(error);

return;
}

if (typeof event === 'string') {
reject(`Error loading script: ${event}`);

reject(new Error(`Error loading script: ${event}`));
return;
}

if (event instanceof Event) {
const target = event.target as Element;
const src = target.getAttribute('src') ?? '';

reject(`Error loading script: ${src}`);

const targetSrc = target.getAttribute('src') ?? '';
reject(new Error(`Error loading script: ${targetSrc}`));
return;
}

reject(`Error loading script`);
reject(new Error(`Error loading script: ${src}`));
};

const ref = document.scripts[0];
Expand Down