How can I test automatically Service Workers in offline mode? Trying with Cypress

Viewed 697

I developed some service workers but when the complex of the service workers (SW) is getting higher I want to create a tests battery to check it out regularly.

I decided to use Cypress in first instance. But I struggle with some problems that dont let me handle the situation.

  1. Offline mode. Cypress has no native use case but has a recipe for Chrome (it doesnt matter if it works only in a unique browser)
  2. When offline mode recipe is active the fetch doesn't work properly on the test.

Cypress Open Issues - Simulate offline mode #235

Cypress Offline Mode Recipe for Chrome

The same web works on the browser but not in the cypress test.

Cypress test code

it('can load if sw registered and try to visit', () => {
   cy.visit(folder)
   cy.contains('#sw-status', 'SW not registered')
   cy.get('#register').click().wait(1000)
      
   Cypress.goOffline()
   Cypress.assertOffline()
      
      
   cy.get('#fetch').click()
   cy.contains('#fetch-response', '200')
})

Exception catched on cypress - Failed to fetch Cypress - Fetch not working. Exception

No internet. Firefox can use the fetch Firefox Fetch Ok

No internet. Chrome can use the fetch Chrome Fetch Ok

Something weird. With no internet Chrome said window.navigator.onLine is true window.navigator.onLine differs Firefox/Chrome

Any suggestion? Try with another testing framework?

I think the explanation of the problem is full and complete, but if someone thinks could be useful I can share code without problems

1 Answers

After a while I did a deeper search in the cypress issues.

I found a comment talking about a problem in some situations when NOT using localhost as server name (I was using custom TLD with Valet for Linux, so it was very related to my problem). I hope that if you are in my situation you don't need to dive in along the same process.

So I check with the new configuration and MAGICALLY all works!.

All i did is Boot up a server using localhost and then run the tests(automatically or with cypress UI)

// package.json
// 'npm test' to run tests automatically
// 'npm run test:ui' to run with cypress UI 
"scripts": {
    "start": "http-server -a localhost -p 3030 -c-1",
    "cy:run": "cypress run",
    "cy:ui": "cypress open",
    "test": "start-server-and-test start http://localhost:3030 cy:run",
    "test:ui": "start-server-and-test start http://localhost:3030 cy:ui",
  },`

I have shared the first attempts in a repository.

Dune Browsing - Exploring testability of service workers in offline mode.

Related