如何在离线模式下自动测试 Service Worker?尝试赛普拉斯

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

我开发了一些服务人员,但是当服务人员 (SW) 的复杂性越来越高时,我想创建一个测试电池来定期检查它。

我决定首先使用 Cypress。但是我遇到了一些让我无法处理的问题。

  1. 离线模式。赛普拉斯没有原生用例,但有一个 Chrome 的配方(如果它只在一个独特的浏览器中工作并不重要)
  2. 当离线模式配方处于活动状态时,提取在测试中无法正常工作。

Cypress Open Issues - Simulate offline mode #235

Cypress Offline Mode Recipe for Chrome

同样的网站在浏览器上运行,但在 cypress 测试中却不行。

赛普拉斯测试代码

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')
})

在 cypress 上捕获异常 - 获取失败

没有网络。 Firefox 可以使用 fetch

没有网络。 Chrome 可以使用fetch

有点奇怪。没有互联网 Chrome 说 window.navigator.onLine 是真的

有什么建议吗?尝试使用其他测试框架?

我认为问题的解释很完整,但如果有人认为可能有用,我可以毫无问题地分享代码

一段时间后,我对柏树问题进行了更深入的搜索。

我找到了一个comment talking about a problem in some situations when NOT using localhost as server name (I was using custom TLD with Valet for Linux,所以它与我的问题非常相关)。我希望如果你处于我的情况,你不需要沿着相同的过程潜入。

所以我检查了新配置,神奇地一切正常!

我所做的就是使用 localhost 启动服务器,然后 运行 测试(自动或使用 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",
  },`

我已经在存储库中分享了第一次尝试。

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