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"]')