diff --git a/packages/govuk-frontend/src/govuk/components/skip-link/skip-link.mjs b/packages/govuk-frontend/src/govuk/components/skip-link/skip-link.mjs index d477a25b4a..8d4db24fc4 100644 --- a/packages/govuk-frontend/src/govuk/components/skip-link/skip-link.mjs +++ b/packages/govuk-frontend/src/govuk/components/skip-link/skip-link.mjs @@ -21,6 +21,7 @@ export class SkipLink extends GOVUKFrontendComponent { /** * @param {Element} $module - HTML element to use for skip link + * @throws {MissingElementError} If the element with the specified ID is not found */ constructor($module) { super() @@ -35,12 +36,9 @@ export class SkipLink extends GOVUKFrontendComponent { try { const $linkedElement = this.getLinkedElement() this.$linkedElement = $linkedElement - } catch (cause) { + } catch (err) { throw new MissingElementError( - 'Skip link: the linked HTML element does not exist', - { - cause: cause instanceof Error ? cause : undefined - } + `Skip link: ${err instanceof Error ? err.message : ''}` ) } @@ -52,23 +50,19 @@ export class SkipLink extends GOVUKFrontendComponent { * * @private * @throws {Error} If the "href" attribute does not contain a hash - * @throws {Error} If the element with the specified ID does not exist + * @throws {TypeError} If the element with the specified ID is not found * @returns {HTMLElement} $linkedElement - DOM element linked to from the skip link */ getLinkedElement() { const linkedElementId = this.getFragmentFromUrl() if (!linkedElementId) { - throw new Error( - `Skip link: $module "href" attribute does not contain a hash` - ) + throw new Error(`$module "href" attribute does not contain a hash`) } const linkedElement = document.getElementById(linkedElementId) if (!linkedElement) { - throw new Error( - `Skip link: Target selector "#${linkedElementId}" not found` - ) + throw new TypeError(`Target selector "#${linkedElementId}" not found`) } return linkedElement diff --git a/packages/govuk-frontend/src/govuk/components/skip-link/skip-link.test.js b/packages/govuk-frontend/src/govuk/components/skip-link/skip-link.test.js index b3e3cf1e56..9e0cef51dc 100644 --- a/packages/govuk-frontend/src/govuk/components/skip-link/skip-link.test.js +++ b/packages/govuk-frontend/src/govuk/components/skip-link/skip-link.test.js @@ -92,7 +92,22 @@ describe('Skip Link', () => { }) ).rejects.toEqual({ name: 'MissingElementError', - message: 'Skip link: the linked HTML element does not exist' + message: + 'Skip link: Target selector "#this-element-does-not-exist" not found' + }) + }) + + it('throws when the href does not contain a hash', async () => { + await expect( + renderAndInitialise(page, 'skip-link', { + params: { + text: 'Skip to main content', + href: 'this-element-does-not-exist' + } + }) + ).rejects.toEqual({ + name: 'MissingElementError', + message: 'Skip link: $module "href" attribute does not contain a hash' }) }) })