diff --git a/app/assets/javascripts/errorBanner.js b/app/assets/javascripts/errorBanner.js new file mode 100644 index 000000000..2b3c259cc --- /dev/null +++ b/app/assets/javascripts/errorBanner.js @@ -0,0 +1,18 @@ +(function (window) { + "use strict"; + + /* + This module is intended to be used to show and hide an error banner based on a javascript trigger. You should make + sure the banner has an appropriate aria-live attribute, and a tabindex of -1 so that screenreaders and keyboard users + are alerted to the change respectively. + + This may behave in unexpected ways if you have more than one element with the `banner-dangerous` class on your page. + */ + window.GOVUK.ErrorBanner = { + hideBanner: () => $('.banner-dangerous').addClass('govuk-!-display-none'), + showBanner: (errorMessage) => $('.banner-dangerous') + .html(`Error: ${errorMessage}`) + .removeClass('govuk-!-display-none') + .trigger('focus'), + }; +})(window); diff --git a/gulpfile.js b/gulpfile.js index 22ebff748..35b51964e 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -182,6 +182,7 @@ const javascripts = () => { paths.src + 'javascripts/registerSecurityKey.js', paths.src + 'javascripts/authenticateSecurityKey.js', paths.src + 'javascripts/updateStatus.js', + paths.src + 'javascripts/errorBanner.js', paths.src + 'javascripts/homepage.js', paths.src + 'javascripts/main.js', ]) diff --git a/tests/javascripts/errorBanner.test.js b/tests/javascripts/errorBanner.test.js new file mode 100644 index 000000000..e80b49811 --- /dev/null +++ b/tests/javascripts/errorBanner.test.js @@ -0,0 +1,41 @@ +beforeAll(() => { + require('../../app/assets/javascripts/errorBanner.js') +}); + +afterAll(() => { + require('./support/teardown.js'); +}); + +describe("Error Banner", () => { + afterEach(() => { + document.body.innerHTML = ''; + }); + + describe("The `hideBanner` method", () => { + test("Will hide the element", () => { + document.body.innerHTML = ` + `; + window.GOVUK.ErrorBanner.hideBanner(); + expect(document.querySelector('.banner-dangerous').classList).toContain('govuk-!-display-none') + }); + }); + + describe("The `showBanner` method", () => { + beforeEach(() => { + document.body.innerHTML = ` + `; + + window.GOVUK.ErrorBanner.showBanner('Some Err'); + }); + + test("Will set a specific error message on the element", () => { + expect(document.querySelector('.banner-dangerous').textContent).toEqual('Error: Some Err') + }); + + test("Will show the element", () => { + expect(document.querySelector('.banner-dangerous').classList).not.toContain('govuk-!-display-none') + }); + }); +});