diff --git a/src/govuk/components/error-summary/error-summary.mjs b/src/govuk/components/error-summary/error-summary.mjs index 61626574d3..0848a6306c 100644 --- a/src/govuk/components/error-summary/error-summary.mjs +++ b/src/govuk/components/error-summary/error-summary.mjs @@ -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 = { diff --git a/src/govuk/components/error-summary/error-summary.test.js b/src/govuk/components/error-summary/error-summary.test.js index fe029071d9..4327f2bb4f 100644 --- a/src/govuk/components/error-summary/error-summary.test.js +++ b/src/govuk/components/error-summary/error-summary.test.js @@ -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', {