Skip to content

Commit

Permalink
Treat the case when there's not internet connection
Browse files Browse the repository at this point in the history
And test that it works.
  • Loading branch information
wlsf82 committed Jan 18, 2024
1 parent 5facb95 commit f3ed35d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
14 changes: 14 additions & 0 deletions cypress/e2e/playground.cy.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
15 changes: 14 additions & 1 deletion src/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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"]')
Expand Down

0 comments on commit f3ed35d

Please sign in to comment.