diff --git a/app/assets/javascripts/govuk_publishing_components/modules.js b/app/assets/javascripts/govuk_publishing_components/modules.js index 5173527fa2..8c2f67c07b 100644 --- a/app/assets/javascripts/govuk_publishing_components/modules.js +++ b/app/assets/javascripts/govuk_publishing_components/modules.js @@ -38,8 +38,13 @@ if (typeof GOVUK.Modules[moduleName] === 'function' && !started) { // Vanilla JavaScript GOV.UK Modules and GOV.UK Frontend Modules if (GOVUK.Modules[moduleName].prototype.init) { - new GOVUK.Modules[moduleName](element).init() - element.setAttribute('data-' + moduleNames[j] + '-module-started', true) + try { + new GOVUK.Modules[moduleName](element).init() + element.setAttribute('data-' + moduleNames[j] + '-module-started', true) + } catch (e) { + // if there's a problem with the module, don't start it + console.error('Error starting ' + moduleName + ' component JS: ' + e.message, window.location) + } } } } diff --git a/spec/javascripts/govuk_publishing_components/modules.spec.js b/spec/javascripts/govuk_publishing_components/modules.spec.js index 27e4bf72e9..6b777d0af3 100644 --- a/spec/javascripts/govuk_publishing_components/modules.spec.js +++ b/spec/javascripts/govuk_publishing_components/modules.spec.js @@ -121,6 +121,16 @@ describe('GOVUK Modules', function () { } GOVUK.Modules.TestCookieDependencyModule = TestCookieDependencyModule + // module with a deliberate error in it + function TestErrorModule (element) { + this.element = element + } + TestErrorModule.prototype.init = function () { + throw new Error('This is a deliberate error') + callbackGemFrontendModule(this.element) + } + GOVUK.Modules.TestErrorModule = TestErrorModule + container = $('
') }) @@ -129,6 +139,7 @@ describe('GOVUK Modules', function () { delete GOVUK.Modules.GemTestAlertFrontendModule delete GOVUK.Modules.TestAlertPublishingAndFrontendModule delete GOVUK.Modules.TestCookieDependencyModule + delete GOVUK.Modules.TestErrorModule container.remove() }) @@ -209,5 +220,16 @@ describe('GOVUK Modules', function () { window.GOVUK.triggerEvent(window, 'cookie-consent') expect(callbackFrontendModule.calls.count()).toBe(2) }) + + it('detects errors in modules and continues without failing', function () { + var module1 = $('') + var module2 = $('') + container.append(module1) + container.append(module2) + $('body').append(container) + + GOVUK.modules.start(container[0]) + expect(callbackGemFrontendModule.calls.count()).toBe(1) + }) }) })