diff --git a/app/assets/javascripts/timeoutPopup.js b/app/assets/javascripts/timeoutPopup.js index f8b5b4cee..75f3cfc38 100644 --- a/app/assets/javascripts/timeoutPopup.js +++ b/app/assets/javascripts/timeoutPopup.js @@ -1,7 +1,12 @@ +window.GOVUK = window.GOVUK || {}; +window.GOVUK.Modules = window.GOVUK.Modules || {}; +window.GOVUK.Modules.TimeoutPopup = window.GOVUK.Modules.TimeoutPopup || {}; + (function(global) { "use strict"; const sessionTimer = document.getElementById("sessionTimer"); + let intervalId = null; function checkTimer(timeTillSessionEnd) { var now = new Date().getTime(); @@ -13,7 +18,8 @@ document.getElementById("logOutTimer").addEventListener("click", logoutUser); document.getElementById("extendSessionTimer").addEventListener("click", extendSession); if (difference < 0) { - clearInterval(x); + clearInterval(intervalId); + intervalId = null; closeTimer(); logoutUser(); } @@ -35,12 +41,14 @@ sessionTimer.close(); } - global.GOVUK.Modules.TimeoutPopup = function() { - setTimeout(function() { - var timeTillSessionEnd = new Date().getTime() + (5 * 60 * 1000); - var x = setInterval(checkTimer, 1000, timeTillSessionEnd); - }, 25 * 60 * 1000); - }; + function setSessionTimer() { + var timeTillSessionEnd = new Date().getTime() + (5 * 60 * 1000); + intervalId = setInterval(checkTimer, 1000, timeTillSessionEnd); + } + + if (document.getElementById("timeLeft") !== null) { + setTimeout(setSessionTimer, 60 * 1000); + } global.GOVUK.Modules.TimeoutPopup.checkTimer = checkTimer; global.GOVUK.Modules.TimeoutPopup.logoutUser = logoutUser; diff --git a/tests/javascripts/timeoutPopup.test.js b/tests/javascripts/timeoutPopup.test.js index 30902c91a..98589a8a7 100644 --- a/tests/javascripts/timeoutPopup.test.js +++ b/tests/javascripts/timeoutPopup.test.js @@ -1,5 +1,4 @@ beforeAll(() => { - jest.useFakeTimers(); jest.spyOn(global, 'setTimeout'); document.body.innerHTML = ` @@ -40,13 +39,24 @@ beforeAll(() => { }); afterAll(() => { - jest.useRealTimers(); document.body.innerHTML = ''; }); -describe('When an authenticated user', () => { - test('does whatever', () => { +describe('When the session timer module is loaded', () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useFakeTimers(); + }); + + test('everything initializes properly', () => { + const sessionTimer = document.getElementById("sessionTimer"); + sessionTimer.showModal = jest.fn(); + sessionTimer.close = jest.fn(); + jest.runAllTimers(); }); @@ -54,6 +64,14 @@ describe('When an authenticated user', () => { describe('The session timer ', () => { + beforeEach(() => { + jest.useFakeTimers(); + }); + + afterEach(() => { + jest.useFakeTimers(); + }); + test('logoutUser method logs the user out', () => { const logoutUserMethod = window.GOVUK.Modules.TimeoutPopup.logoutUser;