diff --git a/packages/govuk-frontend/src/govuk/init.jsdom.test.mjs b/packages/govuk-frontend/src/govuk/init.jsdom.test.mjs index c837b24b84..12363440fd 100644 --- a/packages/govuk-frontend/src/govuk/init.jsdom.test.mjs +++ b/packages/govuk-frontend/src/govuk/init.jsdom.test.mjs @@ -307,6 +307,38 @@ describe('createAll', () => { } } + it('executes callback if specified', () => { + document.body.innerHTML = `
` + + const errorCallback = jest.fn((error, context) => { + console.log(error) + console.log(context) + }) + + // Silence warnings in test output, and allow us to 'expect' them + jest.spyOn(global.console, 'log').mockImplementation() + + expect(() => { + createAll( + MockComponentThatErrors, + { attribute: 'random' }, + document, + errorCallback + ) + }).not.toThrow() + + expect(errorCallback).toHaveBeenCalled() + + expect(global.console.log).toHaveBeenCalledWith(expect.any(Error)) + expect(global.console.log).toHaveBeenCalledWith( + expect.objectContaining({ + component: MockComponentThatErrors, + config: { attribute: 'random' }, + element: document.querySelector('[data-module="mock-component"]') + }) + ) + }) + it('catches errors thrown by components and logs them to the console', () => { document.body.innerHTML = `` diff --git a/packages/govuk-frontend/src/govuk/init.mjs b/packages/govuk-frontend/src/govuk/init.mjs index c909684568..6b51ea3137 100644 --- a/packages/govuk-frontend/src/govuk/init.mjs +++ b/packages/govuk-frontend/src/govuk/init.mjs @@ -54,6 +54,13 @@ function initAll(config) { }) } +/** + * @template {CompatibleClass} T + * @callback errorCallback + * @param {Error} error - Thrown error + * @param {ErrorContext