Skip to content

Commit

Permalink
Use error message strings instead of cause
Browse files Browse the repository at this point in the history
  • Loading branch information
domoscargin committed Sep 7, 2023
1 parent c61fb5a commit 92b7643
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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 : ''}`
)
}

Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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'
})
})
})
Expand Down

0 comments on commit 92b7643

Please sign in to comment.