diff --git a/app/assets/javascripts/activityChart.js b/app/assets/javascripts/activityChart.js index be15a3aad..cf48d091a 100644 --- a/app/assets/javascripts/activityChart.js +++ b/app/assets/javascripts/activityChart.js @@ -5,6 +5,9 @@ const tableContainer = document.getElementById('activityContainer'); const currentUserName = tableContainer.getAttribute('data-currentUserName'); const currentServiceId = tableContainer.getAttribute('data-currentServiceId'); + let pollInterval; + let isPolling = false; + const POLL_INTERVAL_MS = 25000; const COLORS = { delivered: '#0076d6', failed: '#fa9441', @@ -153,8 +156,6 @@ .on('mouseout', function() { tooltip.style('display', 'none'); }) - .transition() - .duration(1000) .attr('y', d => y(d[1])) .attr('height', d => { const calculatedHeight = y(d[0]) - y(d[1]); @@ -209,28 +210,35 @@ table.append(tbody); }; - const fetchData = function(type) { + const fetchData = async function(type) { + if (isPolling) { + return; + } + + if (document.hidden) { + return; + } var ctx = document.getElementById('weeklyChart'); if (!ctx) { return; } + isPolling = true; + var userTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; var url = type === 'service' ? `/services/${currentServiceId}/daily-stats.json?timezone=${encodeURIComponent(userTimezone)}` : `/services/${currentServiceId}/daily-stats-by-user.json?timezone=${encodeURIComponent(userTimezone)}`; + try { + const response = await fetch(url); + if (!response.ok) { + throw new Error('Network response was not ok'); + } - return fetch(url) - .then(response => { - if (!response.ok) { - throw new Error('Network response was not ok'); - } - return response.json(); - }) - .then(data => { + const data = await response.json(); labels = []; deliveredData = []; failedData = []; @@ -277,10 +285,41 @@ } return data; - }) - .catch(error => console.error('Error fetching daily stats:', error)); - }; - setInterval(() => fetchData(currentType), 25000); + } catch (error) { + console.error('Error fetching daily stats:', error); + } finally { + isPolling = false; + } + }; + + function startPolling() { + fetchData(currentType); + + pollInterval = setInterval(() => { + fetchData(currentType); + }, POLL_INTERVAL_MS); + } + + function stopPolling() { + if (pollInterval) { + clearInterval(pollInterval); + pollInterval = null; + } + } + + document.addEventListener('visibilitychange', () => { + if (document.hidden) { + stopPolling(); + } else { + stopPolling(); + startPolling(); + } + }); + + if (typeof jest === 'undefined') { + startPolling(); + } + const handleDropdownChange = function(event) { const selectedValue = event.target.value; currentType = selectedValue; diff --git a/app/assets/javascripts/modules/all.mjs b/app/assets/javascripts/modules/all.mjs index 6312f03dc..2d64ae97e 100644 --- a/app/assets/javascripts/modules/all.mjs +++ b/app/assets/javascripts/modules/all.mjs @@ -14,7 +14,6 @@ import Button from 'govuk-frontend/components/button/button'; import Radios from 'govuk-frontend/components/radios/radios'; // Modules from 3rd party vendors -import morphdom from 'morphdom'; /** * TODO: Ideally this would be a NodeList.prototype.forEach polyfill @@ -67,13 +66,8 @@ var Frontend = { "initAll": initAll } -var vendor = { - "morphdom": morphdom -} - // The exported object will be assigned to window.GOVUK in our production code // (bundled into an IIFE by RollupJS) export { - Frontend, - vendor + Frontend } diff --git a/app/assets/javascripts/socketio.js b/app/assets/javascripts/socketio.js index 754ea5c01..b7492b277 100644 --- a/app/assets/javascripts/socketio.js +++ b/app/assets/javascripts/socketio.js @@ -1,11 +1,3 @@ -function debounce(func, wait) { - let timeout; - return function (...args) { - clearTimeout(timeout); - timeout = setTimeout(() => func.apply(this, args), wait); - }; -} - document.addEventListener('DOMContentLoaded', function () { const isJobPage = window.location.pathname.includes('/jobs/'); if (!isJobPage) return; @@ -15,69 +7,115 @@ document.addEventListener('DOMContentLoaded', function () { const featureEnabled = jobEl?.dataset?.feature === 'true'; const apiHost = jobEl?.dataset?.host; - if (!jobId) return; + if (!jobId || !featureEnabled) return; - if (featureEnabled) { - const socket = io(apiHost); + const DEFAULT_INTERVAL_MS = 10000; + const MIN_INTERVAL_MS = 1000; + const MAX_INTERVAL_MS = 30000; - socket.on('connect_error', (err) => { - console.error('Socket connect_error:', err); - }); + let pollInterval; + let currentInterval = DEFAULT_INTERVAL_MS; + let isPolling = false; - socket.on('error', (err) => { - console.error('Socket error:', err); - }); - - socket.on('connect', () => { - socket.emit('join', { room: `job-${jobId}` }); - }); - - window.addEventListener('beforeunload', () => { - socket.emit('leave', { room: `job-${jobId}` }); - }); - - const debouncedUpdate = debounce((data) => { - updateAllJobSections(); - }, 1000); - - socket.on('job_updated', (data) => { - if (data.job_id !== jobId) return; - debouncedUpdate(data); - }); + function calculateBackoff(responseTime) { + return Math.min( + MAX_INTERVAL_MS, + Math.max( + MIN_INTERVAL_MS, + Math.floor((250 * Math.sqrt(responseTime)) - 1000) + ) + ); } - function updateAllJobSections() { + async function updateAllJobSections() { + if (isPolling || document.hidden) { + return; + } + + isPolling = true; + const startTime = Date.now(); + const resourceEl = document.querySelector('[data-socket-update="status"]'); const url = resourceEl?.dataset?.resource; if (!url) { - console.warn('No resource URL found for job updates'); + isPolling = false; return; } - fetch(url) - .then((res) => res.json()) - .then(({ status, counts, notifications }) => { - const sections = { - status: document.querySelector('[data-socket-update="status"]'), - counts: document.querySelector('[data-socket-update="counts"]'), - notifications: document.querySelector( - '[data-socket-update="notifications"]' - ), - }; + try { + const response = await fetch(url); + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + const data = await response.json(); - if (status && sections.status) { - sections.status.innerHTML = status; - } - if (counts && sections.counts) { - sections.counts.innerHTML = counts; - } - if (notifications && sections.notifications) { - sections.notifications.innerHTML = notifications; - } - }) - .catch((err) => { - console.error('Error fetching job update partials:', err); + const sections = { + status: document.querySelector('[data-socket-update="status"]'), + counts: document.querySelector('[data-socket-update="counts"]'), + notifications: document.querySelector('[data-socket-update="notifications"]'), + }; + + if (data.status && sections.status) { + sections.status.innerHTML = data.status; + } + if (data.counts && sections.counts) { + sections.counts.innerHTML = data.counts; + } + if (data.notifications && sections.notifications) { + sections.notifications.innerHTML = data.notifications; + } + + const responseTime = Date.now() - startTime; + currentInterval = calculateBackoff(responseTime); + + if (data.stop === 1 || data.finished === true) { + stopPolling(); + } + + } catch (error) { + console.error('Error fetching job updates:', { + error: error.message, + url: url, + jobId: jobId, + timestamp: new Date().toISOString() }); + currentInterval = Math.min(currentInterval * 2, MAX_INTERVAL_MS); + } finally { + isPolling = false; + } } + + function startPolling() { + updateAllJobSections(); + + function scheduleNext() { + if (pollInterval) clearTimeout(pollInterval); + pollInterval = setTimeout(() => { + updateAllJobSections(); + scheduleNext(); + }, currentInterval); + } + + scheduleNext(); + } + + function stopPolling() { + if (pollInterval) { + clearTimeout(pollInterval); + pollInterval = null; + } + } + + document.addEventListener('visibilitychange', () => { + if (document.hidden) { + stopPolling(); + } else { + startPolling(); + } + }); + + window.addEventListener('beforeunload', stopPolling); + + startPolling(); }); diff --git a/app/assets/javascripts/updateContent.js b/app/assets/javascripts/updateContent.js deleted file mode 100644 index d488cd9a2..000000000 --- a/app/assets/javascripts/updateContent.js +++ /dev/null @@ -1,148 +0,0 @@ -(function(global) { - "use strict"; - - var queues = {}; - var morphdom = global.GOVUK.vendor.morphdom; - var defaultInterval = 2000; - var interval = 0; - - var calculateBackoff = responseTime => parseInt(Math.max( - (250 * Math.sqrt(responseTime)) - 1000, - 1000 - )); - - // Methods to ensure the DOM fragment is clean of classes added by JS before diffing - // and that they are replaced afterwards. - // - // Added to allow the use of JS, in main.js, to apply styles which in future could be - // achieved with the :has pseudo-class. If :has is available in our supported browsers, - // this can be removed in favour of a CSS-only solution. - var ClassesPersister = function ($contents) { - this._$contents = $contents; - this._classNames = []; - this._classesTo$ElsMap = {}; - }; - ClassesPersister.prototype.addClassName = function (className) { - if (this._classNames.indexOf(className) === -1) { - this._classNames.push(className); - } - }; - ClassesPersister.prototype.remove = function () { - // Store references to any elements with class names to persist - this._classNames.forEach(className => { - var $elsWithClassName = $('.' + className, this._$contents).removeClass(className); - - if ($elsWithClassName.length > 0) { - this._classesTo$ElsMap[className] = $elsWithClassName; - } - }); - }; - ClassesPersister.prototype.replace = function () { - var replaceClasses = (idx, el) => { - - // Avoid updating elements that are no longer present. - // elements removed will still exist in memory but won't be attached to the DOM any more - if (global.document.body.contains(el)) { - $(el).addClass(className); - } - - }; - var className; - - for (className in this._classesTo$ElsMap) { - this._classesTo$ElsMap[className].each(replaceClasses); - } - - // remove references to elements - this._classesTo$ElsMap = {}; - }; - - var getRenderer = ($contents, key, classesPersister) => response => { - classesPersister.remove(); - morphdom( - $contents.get(0), - $(response[key]).get(0) - ); - classesPersister.replace(); - }; - - var getQueue = resource => ( - queues[resource] = queues[resource] || [] - ); - - var flushQueue = function(queue, response) { - while(queue.length) queue.shift()(response); - }; - - var clearQueue = queue => (queue.length = 0); - - var poll = function(renderer, resource, queue, form) { - - let startTime = Date.now(); - - if (document.visibilityState !== "hidden" && queue.push(renderer) === 1) { - $.ajax( - resource, - { - 'method': form ? 'post' : 'get', - 'data': form ? $('#' + form).serialize() : {} - } - ).done( - response => { - flushQueue(queue, response); - if (response.stop === 1) { - poll = function(){}; - } - interval = calculateBackoff(Date.now() - startTime); - } - ).fail( - () => poll = function(){} - ); - } - - setTimeout( - () => poll.apply(window, arguments), interval - ); - }; - - global.GOVUK.Modules.UpdateContent = function() { - - this.start = component => { - var $component = $(component); - var $contents = $component.children().eq(0); - var key = $component.data('key'); - var resource = $component.data('resource'); - var form = $component.data('form'); - var classesPersister = new ClassesPersister($contents); - - // Replace component with contents. - // The renderer does this anyway when diffing against the first response - $component.replaceWith($contents); - - // Store any classes that should persist through updates - // - // Added to allow the use of JS, in main.js, to apply styles which in future could be - // achieved with the :has pseudo-class. If :has is available in our supported browsers, - // this can be removed in favour of a CSS-only solution. - if ($contents.data('classesToPersist') !== undefined) { - $contents.data('classesToPersist') - .split(' ') - .forEach(className => classesPersister.addClassName(className)); - } - - setTimeout( - () => poll( - getRenderer($contents, key, classesPersister), - resource, - getQueue(resource), - form - ), - defaultInterval - ); - }; - - }; - - global.GOVUK.Modules.UpdateContent.calculateBackoff = calculateBackoff; - -})(window); diff --git a/app/templates/components/ajax-block.html b/app/templates/components/ajax-block.html index c73978725..f85fc5ff3 100644 --- a/app/templates/components/ajax-block.html +++ b/app/templates/components/ajax-block.html @@ -1,14 +1,3 @@ {% macro ajax_block(partials, url, key, finished=False, form='') %} - {% if not finished %} -
- {% endif %} - {{ partials[key]|safe }} - {% if not finished %} -
- {% endif %} + {{ partials[key]|safe }} {% endmacro %} diff --git a/app/templates/views/jobs/job.html b/app/templates/views/jobs/job.html index f9a6a3fed..38ff39162 100644 --- a/app/templates/views/jobs/job.html +++ b/app/templates/views/jobs/job.html @@ -15,56 +15,44 @@

This page refreshes automatically to show the latest message activity delivery rates, details, and reports.
You can watch it in progress or check back later.

{% endif %}
- {% if not job.finished_processing %} + {% if not job.finished_processing and FEATURE_SOCKET_ENABLED %}
{% endif %} {{ partials['status']|safe }} - {% if not job.finished_processing %} + {% if not job.finished_processing and FEATURE_SOCKET_ENABLED %}
{% endif %} - {% if not finished %} + {% if not finished and FEATURE_SOCKET_ENABLED %}
{% endif %} {{ partials['counts']|safe }} - {% if not finished %} + {% if not finished and FEATURE_SOCKET_ENABLED %}
{% endif %}

Messages are sent immediately to the cell phone carrier, but will remain in "pending" status until we hear back from the carrier they have received it and attempted deliver. More information on delivery status.

- {% if not job.processing_finished %} + {% if not job.processing_finished and FEATURE_SOCKET_ENABLED %}
{% endif %} {{ partials['notifications']|safe }} - {% if not job.processing_finished %} + {% if not job.processing_finished and FEATURE_SOCKET_ENABLED %}
{% endif %}
diff --git a/gulpfile.js b/gulpfile.js index 78b76640f..a49f7d1ad 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -60,7 +60,6 @@ const javascripts = () => { paths.src + 'javascripts/enhancedTextbox.js', paths.src + 'javascripts/fileUpload.js', paths.src + 'javascripts/radioSelect.js', - paths.src + 'javascripts/updateContent.js', paths.src + 'javascripts/listEntry.js', paths.src + 'javascripts/liveSearch.js', paths.src + 'javascripts/errorTracking.js', diff --git a/package-lock.json b/package-lock.json index 77c8f744f..a8f81fadc 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,7 +19,6 @@ "govuk-frontend": "2.13.0", "gulp-merge": "^0.1.1", "jquery": "3.7.1", - "morphdom": "^2.7.7", "playwright": "^1.55.0", "python": "^0.0.4", "query-command-supported": "1.0.0", @@ -11204,12 +11203,6 @@ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==", "dev": true }, - "node_modules/morphdom": { - "version": "2.7.7", - "resolved": "https://registry.npmjs.org/morphdom/-/morphdom-2.7.7.tgz", - "integrity": "sha512-04GmsiBcalrSCNmzfo+UjU8tt3PhZJKzcOy+r1FlGA7/zri8wre3I1WkYN9PT3sIeIKfW9bpyElA+VzOg2E24g==", - "license": "MIT" - }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", diff --git a/package.json b/package.json index 9afd66ee8..0d66c4298 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,6 @@ "govuk-frontend": "2.13.0", "gulp-merge": "^0.1.1", "jquery": "3.7.1", - "morphdom": "^2.7.7", "playwright": "^1.55.0", "python": "^0.0.4", "query-command-supported": "1.0.0", diff --git a/tests/app/main/views/test_activity.py b/tests/app/main/views/test_activity.py index 967bf6edb..4f14c8f87 100644 --- a/tests/app/main/views/test_activity.py +++ b/tests/app/main/views/test_activity.py @@ -167,33 +167,12 @@ def test_can_show_notifications( assert page_title in page.h1.text.strip() - path_to_json = page.find("div", {"data-key": "notifications"})["data-resource"] - - url = urlparse(path_to_json) - assert url.path == "/services/{}/notifications{}".format( - SERVICE_ONE_ID, - expected_update_endpoint, - ) - query_dict = parse_qs(url.query) - if status_argument: - assert query_dict["status"] == [status_argument] - if expected_page_argument: - assert query_dict["page"] == [str(expected_page_argument)] - assert "to" not in query_dict - - mock_get_notifications.assert_called_with( - limit_days=expected_limit_days, - page=expected_page_argument, - service_id=SERVICE_ONE_ID, - status=expected_api_call, - template_type=list(extra_args.values()), - to=expected_to_argument, - ) - json_response = client_request.get_response( "main.get_notifications_as_json", - service_id=service_one["id"], + service_id=SERVICE_ONE_ID, status=status_argument, + page=expected_page_argument, + to=expected_to_argument, **extra_args ) json_content = json.loads(json_response.get_data(as_text=True)) @@ -203,6 +182,8 @@ def test_can_show_notifications( "service_data_retention_days", } + mock_get_notifications.assert_called() + def test_can_show_notifications_if_data_retention_not_available( client_request, @@ -305,6 +286,7 @@ def test_download_links_show_when_data_available( mocker.patch("app.s3_client.check_s3_file_exists", return_value=True) mock_obj = mocker.Mock() mock_obj.content_length = 1024 + mocker.patch("app.s3_client.get_s3_object", return_value=mock_obj) mocker.patch("app.s3_client.s3_csv_client.get_csv_upload", return_value=mock_obj) page = client_request.get( @@ -345,6 +327,7 @@ def test_download_links_partial_data_available( mock_obj = mocker.Mock() mock_obj.content_length = 2048 mocker.patch("app.s3_client.s3_csv_client.get_csv_upload", return_value=mock_obj) + mocker.patch("app.s3_client.get_s3_object", return_value=mock_obj) page = client_request.get( "main.all_jobs_activity", @@ -370,6 +353,9 @@ def test_download_links_no_data_available( mocker.patch("app.job_api_client.get_page_of_jobs", return_value=mock_jobs_empty) mocker.patch("app.job_api_client.get_immediate_jobs", return_value=[]) mocker.patch("app.s3_client.check_s3_file_exists", return_value=False) + mock_obj = mocker.Mock() + mock_obj.content_length = 0 + mocker.patch("app.s3_client.get_s3_object", return_value=mock_obj) page = client_request.get( "main.all_jobs_activity", diff --git a/tests/app/main/views/test_jobs.py b/tests/app/main/views/test_jobs.py index 17bccfc82..391b059c3 100644 --- a/tests/app/main/views/test_jobs.py +++ b/tests/app/main/views/test_jobs.py @@ -92,12 +92,13 @@ def test_should_show_page_for_one_job( assert " ".join(page.find("tbody").find("tr").text.split()) == ( "2021234567 template content Delivered 01-01-2016 at 06:09 AM" ) - assert page.find("div", {"data-key": "notifications"})["data-resource"] == url_for( + client_request.get_response( "main.view_job_updates", service_id=SERVICE_ONE_ID, job_id=fake_uuid, status=status_argument, ) + mock_get_notifications.assert_called() csv_link = page.select_one("a[download]") assert csv_link["href"] == url_for( "main.view_job_csv", diff --git a/tests/javascripts/activityChart.test.js b/tests/javascripts/activityChart.test.js index 4992e2076..6b63951f0 100644 --- a/tests/javascripts/activityChart.test.js +++ b/tests/javascripts/activityChart.test.js @@ -354,3 +354,93 @@ test('handleDropdownChange shows empty message when user has no jobs', () => { window.fetchData.mockRestore(); }); + +test('fetchData returns early when isPolling is true', async () => { + window.isPolling = true; + global.fetch = jest.fn(); + + const result = await window.fetchData('service'); + + expect(global.fetch).not.toHaveBeenCalled(); + expect(result).toBeUndefined(); + + window.isPolling = false; + delete global.fetch; +}); + + +test('fetchData returns early when document is hidden', async () => { + Object.defineProperty(document, 'hidden', { value: true, writable: true }); + global.fetch = jest.fn(); + + const result = await window.fetchData('service'); + + expect(global.fetch).not.toHaveBeenCalled(); + expect(result).toBeUndefined(); + + Object.defineProperty(document, 'hidden', { value: false, writable: true }); + delete global.fetch; +}); + + +test('fetchData returns undefined when weeklyChart is missing', async () => { + const chart = document.getElementById('weeklyChart'); + if (chart) { + chart.remove(); + } + + window.isPolling = false; + global.fetch = jest.fn(); + + const result = await window.fetchData('service'); + + expect(result).toBeUndefined(); + expect(global.fetch).not.toHaveBeenCalled(); + + const container = document.getElementById('activityChart'); + if (container && !document.getElementById('weeklyChart')) { + const newChart = document.createElement('div'); + newChart.id = 'weeklyChart'; + newChart.setAttribute('data-service-id', '12345'); + newChart.style.width = '600px'; + container.appendChild(newChart); + } + + delete global.fetch; +}); + + +test('handleDropdownChange updates subtitle text correctly', () => { + const selectElement = document.getElementById('options'); + selectElement.value = 'individual'; + const event = { target: selectElement }; + + jest.spyOn(window, 'fetchData').mockImplementation(() => {}); + + window.handleDropdownChange(event); + + const subtitle = document.querySelector('#activityChartContainer .chart-subtitle'); + expect(subtitle.textContent).toContain('Individual'); + + window.fetchData.mockRestore(); +}); + +test('dropdown change handles DOM updates for table filtering', () => { + const selectElement = document.getElementById('options'); + + jest.spyOn(window, 'fetchData').mockImplementation(() => {}); + + selectElement.value = 'service'; + window.handleDropdownChange({ target: selectElement }); + + let subtitle = document.querySelector('#activityChartContainer .chart-subtitle'); + expect(subtitle.textContent).toContain('Service'); + + selectElement.value = 'individual'; + window.handleDropdownChange({ target: selectElement }); + + subtitle = document.querySelector('#activityChartContainer .chart-subtitle'); + expect(subtitle.textContent).toContain('Individual'); + + window.fetchData.mockRestore(); +}); diff --git a/tests/javascripts/updateContent.test.js b/tests/javascripts/updateContent.test.js deleted file mode 100644 index f8229f63a..000000000 --- a/tests/javascripts/updateContent.test.js +++ /dev/null @@ -1,513 +0,0 @@ -const each = require('jest-each').default; - -const helpers = require('./support/helpers.js'); - -const serviceNumber = '6658542f-0cad-491f-bec8-ab8457700ead'; -const resourceURL = `/services/${serviceNumber}/notifications/email.json?status=sending%2Cdelivered%2Cfailed`; -const updateKey = 'counts'; - -let responseObj = {}; -let jqueryAJAXReturnObj; - -beforeAll(() => { - - // ensure all timers go through Jest - jest.useFakeTimers(); - - // mock the bits of jQuery used - jest.spyOn(window.$, 'ajax'); - - // set up the object returned from $.ajax so it responds with whatever responseObj is set to - jqueryAJAXReturnObj = { - done: callback => { - // The server takes 1 second to respond - jest.advanceTimersByTime(1000); - callback(responseObj); - return jqueryAJAXReturnObj; - }, - fail: () => {} - }; - - $.ajax.mockImplementation(() => jqueryAJAXReturnObj); - - // RollupJS assigns our bundled module code, including morphdom, to window.GOVUK. - // morphdom is assigned to its vendor property so we need to copy that here for the updateContent - // code to pick it up. - window.GOVUK.vendor = { - morphdom: require('morphdom') - }; - require('../../app/assets/javascripts/updateContent.js'); - -}); - -afterAll(() => { - require('./support/teardown.js'); -}); - -describe('Update content', () => { - - const getInitialHTMLString = partial => ` -
- ${partial} -
`; - - describe("All variations", () => { - - beforeEach(() => { - - // Intentionally basic example because we're not testing changes to the partial - document.body.innerHTML = getInitialHTMLString(`

Sending

`); - - // default the response to match the content inside div[data-module] - responseObj[updateKey] = `

Sending

`; - - }); - - describe("By default", () => { - - beforeEach(() => { - - // start the module - window.GOVUK.modules.start(); - - }); - - test("It should use the GET HTTP method", () => { - - jest.advanceTimersByTime(2000); - expect($.ajax.mock.calls[0][1].method).toEqual('get'); - - }); - - test("It shouldn't send any data as part of the requests", () => { - - jest.advanceTimersByTime(2000); - expect($.ajax.mock.calls[0][1].data).toEqual({}); - - }); - - test("It should request updates with a dynamic interval", () => { - - // First call doesn’t happen in the first 2000ms - jest.advanceTimersByTime(1999); - expect($.ajax).toHaveBeenCalledTimes(0); - - // But it happens after 2000ms by default - jest.advanceTimersByTime(1); - expect($.ajax).toHaveBeenCalledTimes(1); - - // It took the server 1000ms to respond to the first call so we - // will back off – the next call shouldn’t happen in the next 6904ms - jest.advanceTimersByTime(6904); - expect($.ajax).toHaveBeenCalledTimes(1); - - // But it should happen after 6905ms - jest.advanceTimersByTime(1); - expect($.ajax).toHaveBeenCalledTimes(2); - - }); - - each([ - [1000, 0], - [1500, 100], - [4590, 500], - [6905, 1000], - [24000, 10000], - ]).test('It calculates a delay of %dms if the API responds in %dms', (waitTime, responseTime) => { - expect( - window.GOVUK.Modules.UpdateContent.calculateBackoff(responseTime) - ).toBe( - waitTime - ); - }); - - }); - - describe("If a form is used as a source for data, referenced in the data-form attribute", () => { - - beforeEach(() => { - - // Add a form to the page - document.body.innerHTML += ` -
- - -
`; - - // Link the component to the form - document.querySelector('[data-module=update-content]').setAttribute('data-form', 'service'); - - // start the module - window.GOVUK.modules.start(); - - }); - - test("requests should use the same HTTP method as the form", () => { - - jest.advanceTimersByTime(2000); - expect($.ajax.mock.calls[0][1].method).toEqual('post'); - - }) - - test("requests should use the data from the form", () => { - - jest.advanceTimersByTime(2000); - expect($.ajax.mock.calls[0][1].data).toEqual(helpers.getFormDataFromPairs([ - ['serviceName', 'Buckhurst surgery'], - ['serviceNumber', serviceNumber] - ])); - - }) - - }); - - }); - - describe('When updating the contents of DOM nodes', () => { - - let partialData; - - const getPartial = items => { - let pillsHTML = ''; - - items.forEach(item => { - pillsHTML += ` -
  • -
    -
    -
    ${item.count}
    -
    -
    ${item.label}
    -
    -
  • `; - }); - - return ` -
    - -
    `; - }; - - beforeEach(() => { - - partialData = [ - { - count: 0, - label: 'total', - selected: true - }, - { - count: 0, - label: 'sending', - selected: false - }, - { - count: 0, - label: 'delivered', - selected: false - }, - { - count: 0, - label: 'failed', - selected: false - } - ]; - - document.body.innerHTML = getInitialHTMLString(getPartial(partialData)); - - }); - - test("It should replace the original HTML with that of the partial, to match that returned from AJAX responses", () => { - - // default the response to match the content inside div[data-module] - responseObj[updateKey] = getPartial(partialData); - - // start the module - window.GOVUK.modules.start(); - - expect(document.querySelector('.ajax-block-container').parentNode.hasAttribute('data-resource')).toBe(false); - - }); - - test("It should make requests to the URL specified in the data-resource attribute", () => { - - // default the response to match the content inside div[data-module] - responseObj[updateKey] = getPartial(partialData); - - // start the module - window.GOVUK.modules.start(); - jest.advanceTimersByTime(2000); - - expect($.ajax.mock.calls[0][0]).toEqual(resourceURL); - - }); - - test("If the response contains no changes, the DOM should stay the same", () => { - - // send the done callback a response with updates included - responseObj[updateKey] = getPartial(partialData); - - // start the module - window.GOVUK.modules.start(); - jest.advanceTimersByTime(2000); - - // check a sample DOM node is unchanged - expect(document.querySelectorAll('.big-number-number')[0].textContent.trim()).toEqual("0"); - - }); - - test("If the response contains changes, it should update the DOM with them", () => { - - partialData[0].count = 1; - - // send the done callback a response with updates included - responseObj[updateKey] = getPartial(partialData); - - // start the module - window.GOVUK.modules.start(); - jest.advanceTimersByTime(2000); - - // check the right DOM node is updated - expect(document.querySelectorAll('.big-number-number')[0].textContent.trim()).toEqual("1"); - - }); - - }); - - describe("When adding or removing DOM nodes", () => { - - let partialData; - - const getPartial = items => { - - const getItemHTMLString = content => { - var areas = ''; - - content.areas.forEach(area => - areas += "\n" + `
  • ${area}
  • ` - ); - - return ` -
    -
    -

    - ${content.title} -

    -
    -
    - - ${content.hint} - -
    -
    -

    - ${content.status} -

    -
    -
    - -
    -
    `; - }; - - var itemsHTMLString = ''; - - items.forEach(item => itemsHTMLString += "\n" + getItemHTMLString(item)); - - return `
    - ${itemsHTMLString}; -
    -
    `; - - }; - - beforeEach(() => { - - partialData = [ - { - title: "Gas leak", - hint: "There's a gas leak in the local area. Residents should vacate until further notice.", - status: "Waiting for approval", - areas: [ - "Santa Claus Village, Rovaniemi B", - "Santa Claus Village, Rovaniemi C" - ] - } - ]; - - }); - - test("If the response contains no changes, the DOM should stay the same", () => { - - document.body.innerHTML = getInitialHTMLString(getPartial(partialData)); - - // make a response with no changes - responseObj[updateKey] = getPartial(partialData); - - // start the module - window.GOVUK.modules.start(); - jest.advanceTimersByTime(2000); - - // check it has the same number of items - expect(document.querySelectorAll('.file-list').length).toEqual(1); - expect(document.querySelectorAll('.file-list h2 a')[0].textContent.trim()).toEqual("Gas leak"); - - }); - - test("If the response adds a node, the DOM should contain that node", () => { - - document.body.innerHTML = getInitialHTMLString(getPartial(partialData)); - - partialData.push({ - title: "Reservoir flooding template", - hint: "The local reservoir has flooded. All people within 5 miles should move to a safer location.", - status: "Waiting for approval", - areas: [ - "Santa Claus Village, Rovaniemi A", - "Santa Claus Village, Rovaniemi D" - ] - }); - - // make the response have an extra item - responseObj[updateKey] = getPartial(partialData); - - // start the module - window.GOVUK.modules.start(); - jest.advanceTimersByTime(2000); - - // check the node has been added - expect(document.querySelectorAll('.file-list').length).toEqual(2); - expect(document.querySelectorAll('.file-list h2 a')[0].textContent.trim()).toEqual("Gas leak"); - expect(document.querySelectorAll('.file-list h2 a')[1].textContent.trim()).toEqual("Reservoir flooding template"); - - }); - - test("If the response removes a node, the DOM should not contain that node", () => { - - // add another item so we start with 2 - partialData.push({ - title: "Reservoir flooding template", - hint: "The local reservoir has flooded. All people within 5 miles should move to a safer location.", - status: "Waiting for approval", - areas: [ - "Santa Claus Village, Rovaniemi A", - "Santa Claus Village, Rovaniemi D" - ] - }); - - document.body.innerHTML = getInitialHTMLString(getPartial(partialData)); - - // remove the last item - partialData.pop(); - - // default the response to match the content inside div[data-module] - responseObj[updateKey] = getPartial(partialData); - - // start the module - window.GOVUK.modules.start(); - jest.advanceTimersByTime(2000); - - // check the node has been removed - expect(document.querySelectorAll('.file-list').length).toEqual(1); - expect(document.querySelectorAll('.file-list h2 a')[0].textContent.trim()).toEqual("Gas leak"); - - }); - - test("If other scripts have added classes to the DOM, they should persist through updates to a single component", () => { - - document.body.innerHTML = getInitialHTMLString(getPartial(partialData)); - - // mark classes to persist on the partial - document.querySelector('.ajax-block-container').setAttribute('data-classes-to-persist', 'js-child-has-focus'); - - // Add class to indicate focus state of link on parent heading - document.querySelectorAll('.file-list h2')[0].classList.add('js-child-has-focus'); - - // Add an item to trigger an update - partialData.push({ - title: "Reservoir flooding template", - hint: "The local reservoir has flooded. All people within 5 miles should move to a safer location.", - status: "Waiting for approval", - areas: [ - "Santa Claus Village, Rovaniemi A", - "Santa Claus Village, Rovaniemi D" - ] - }); - - // make the response have an extra item - responseObj[updateKey] = getPartial(partialData); - - // start the module - window.GOVUK.modules.start(); - jest.advanceTimersByTime(2000); - - // check the class is still there - expect(document.querySelectorAll('.file-list h2')[0].classList.contains('js-child-has-focus')).toBe(true); - - }); - - test("If other scripts have added classes to the DOM, they should persist through updates to multiple components", () => { - - // Create duplicate components in the page - document.body.innerHTML = getInitialHTMLString(getPartial(partialData)) + "\n" + getInitialHTMLString(getPartial(partialData)); - - var partialsInPage = document.querySelectorAll('.ajax-block-container'); - - // Mark classes to persist on the partials (2nd is made up) - partialsInPage[0].setAttribute('data-classes-to-persist', 'js-child-has-focus'); - partialsInPage[1].setAttribute('data-classes-to-persist', 'js-2nd-child-has-focus'); - - // Add examples of those classes on each partial (2nd is made up) - partialsInPage[0].querySelectorAll('.file-list h2')[0].classList.add('js-child-has-focus'); - partialsInPage[1].querySelectorAll('.file-list h2')[0].classList.add('js-2nd-child-has-focus'); - - // Add an item to trigger an update - partialData.push({ - title: "Reservoir flooding template", - hint: "The local reservoir has flooded. All people within 5 miles should move to a safer location.", - status: "Waiting for approval", - areas: [ - "Santa Claus Village, Rovaniemi A", - "Santa Claus Village, Rovaniemi D" - ] - }); - - // make all responses have an extra item - responseObj[updateKey] = getPartial(partialData); - - // start the module - window.GOVUK.modules.start(); - jest.advanceTimersByTime(2000); - - // re-select in case nodes in partialsInPage have changed - partialsInPage = document.querySelectorAll('.ajax-block-container'); - - // check the classes are still there - expect(partialsInPage[0].querySelectorAll('.file-list h2')[0].classList.contains('js-child-has-focus')).toBe(true); - expect(partialsInPage[1].querySelectorAll('.file-list h2')[0].classList.contains('js-2nd-child-has-focus')).toBe(true); - - // check each heading only has the classes assigned to it before updates occurred - expect(partialsInPage[0].querySelectorAll('.file-list h2')[0].classList.contains('js-2nd-child-has-focus')).toBe(false); - expect(partialsInPage[1].querySelectorAll('.file-list h2')[0].classList.contains('js-child-has-focus')).toBe(false); - - }); - - }); - - afterEach(() => { - - document.body.innerHTML = ''; - - // tidy up record of mocked AJAX calls - $.ajax.mockClear(); - - // ensure any timers set by continually starting the module are cleared - jest.clearAllTimers(); - - }); - -});