From f3ed35d8d4fd9cf84a6b8add7f10175cde3d9be7 Mon Sep 17 00:00:00 2001 From: Walmyr Date: Thu, 18 Jan 2024 23:35:20 +0100 Subject: [PATCH] Treat the case when there's not internet connection And test that it works. --- cypress/e2e/playground.cy.js | 14 ++++++++++++++ src/script.js | 15 ++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/cypress/e2e/playground.cy.js b/cypress/e2e/playground.cy.js index 95e3f21..7d0718b 100644 --- a/cypress/e2e/playground.cy.js +++ b/cypress/e2e/playground.cy.js @@ -128,6 +128,20 @@ describe('Cypress Playground', () => { ).should('be.visible') }) + it('clicks a button and simulate a network failure', () => { + cy.intercept( + 'GET', + 'https://jsonplaceholder.typicode.com/todos/1', + { forceNetworkError: true } + ).as('getTodo') + cy.contains('#intercept button', 'Get TODO').click() + cy.wait('@getTodo') + cy.contains( + '#intercept .error span', + 'Oops, something went wrong. Check your internet connection, refresh the page, and try again.' + ).should('be.visible') + }) + it('makes an HTTP request and asserts on the returned status code', () => { cy.request('GET', 'https://jsonplaceholder.typicode.com/todos/1') .its('status') diff --git a/src/script.js b/src/script.js index 983889c..7271a50 100644 --- a/src/script.js +++ b/src/script.js @@ -88,7 +88,8 @@ document.querySelector('#intercept button') async function mountTodoList() { const interceptDiv = document.getElementById('intercept') - const response = await fetch('https://jsonplaceholder.typicode.com/todos/1') + try { + const response = await fetch('https://jsonplaceholder.typicode.com/todos/1') .then(async response => { if (response.ok) { const body = await response.json() @@ -131,6 +132,18 @@ async function mountTodoList() { .removeEventListener('click', mountTodoList) } }) + } catch { + const errorDiv = document.createElement('div') + const errorSpan = document.createElement('span') + + errorDiv.className = 'error' + errorSpan.innerText = 'Oops, something went wrong. Check your internet connection, refresh the page, and try again.' + interceptDiv.appendChild(errorDiv) + errorDiv.appendChild(errorSpan) + + document.querySelector('#intercept button') + .removeEventListener('click', mountTodoList) + } } document.querySelector('#input-range input[type="range"]')