Skip to content

Commit

Permalink
Safeguard ErrorSummary instantiation without an element
Browse files Browse the repository at this point in the history
This complements the guard within our `initAll` function. It'll protect
users code when:
- they would manually initialise an `ErrorSummary`
- but sometimes not pass an element (because there is none collected
  by a `document.querySelector`, for example).
That'll avoid the JavaScript execution stopping because of the missing element
and their code will carry on running as it does now.
  • Loading branch information
romaricpascal committed Sep 20, 2022
1 parent 06d8949 commit 08abe72
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/govuk/components/error-summary/error-summary.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,19 @@ import { mergeConfigs, normaliseDataset } from '../../common.mjs'
* @param {Boolean} [config.disableAutoFocus=false] - Whether to disable the component taking focus on initialisation
*/
function ErrorSummary ($module, config) {
// Some consuming code may not be passing a module,
// for example if they initialise the component
// on their own by directly passing the result
// of `document.querySelector`.
// To avoid breaking further JavaScript initialisation
// we need to safeguard against this so things keep
// working the same now we read the elements data attributes
if (!$module) {
// Little safety in case code gets ported as-is
// into and ES6 class constructor, where the return value matters
return this
}

this.$module = $module

var defaultConfig = {
Expand Down
15 changes: 15 additions & 0 deletions src/govuk/components/error-summary/error-summary.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,21 @@ describe('Error Summary', () => {
})
})

describe('using JavaScript configuration, with no elements on the page', () => {
it('does not prevent further JavaScript from running', async () => {
const result = await page.evaluate(() => {
// `undefined` simulates the element being missing,
// from an unchecked `document.querySelector` for example
new window.GOVUKFrontend.ErrorSummary(undefined).init()

// If our component initialisation breaks, this won't run
return true
})

expect(result).toBe(true)
})
})

describe('using JavaScript configuration, but enabled via data-attributes', () => {
beforeAll(async () => {
await renderAndInitialise('error-summary', {
Expand Down

0 comments on commit 08abe72

Please sign in to comment.