Files
image-workbench-desktop/tests/iwb-sw-update.spec.js
T

54 lines
2.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict'
// Service Worker 更新检测路径(2026-11-07)
//
// 背景:应用外壳缓存(离线可用)已于同日**移除** —— 实测在真实浏览器里出现
// 「普通刷新白屏 / 强刷才好」的升级时序问题,而离线场景下图片本就无法生成,
// 价值不抵风险。SW 回到最小职责:**只做版本更新检测**(不拦截任何文档/资源请求)。
//
// 本 spec 钉住这条仍存在的链路(发版后用户能否拿到新版本全靠它):
// ① sw.js 内容变化(模拟发版)⇒ 新 SW 进入 waiting
// ② 前端 SKIP_WAITING ⇒ 激活后页面正常渲染(升级不白屏)
// 若将来重新引入外壳缓存,需同时恢复按版本隔离 + 导航永不失败的守卫(见 git 历史 310b91f)。
const fs = require('fs')
const path = require('path')
const { test, expect } = require('./_pw-coverage')
test.use({ baseURL: 'http://127.0.0.1:8787', viewport: { width: 1280, height: 800 } })
const dist = path.join(__dirname, '..', 'dist')
const swPath = path.join(dist, 'sw.js')
test('SW 更新检测:版本变化 → waiting → SKIP_WAITING → 页面正常', async ({ page }) => {
const original = fs.readFileSync(swPath, 'utf8')
try {
await page.addInitScript(() => {
localStorage.clear()
localStorage.setItem('iwb_web_cfg', JSON.stringify({ providers: [], canvas: {} }))
})
await page.goto('/', { waitUntil: 'domcontentloaded' })
await expect.poll(() => page.evaluate(() => !!(navigator.serviceWorker && navigator.serviceWorker.controller)), { timeout: 20000 }).toBe(true)
// ① 模拟"又一次发版":只改 sw.js 的版本串(内容变化 ⇒ 浏览器认为是新 SW)
const bumped = original.replace(/const VERSION = '([^']+)'/, "const VERSION = '$1-e2eupdate'")
expect(bumped).not.toBe(original, 'sw.js 里应有 VERSION 字面量可供替换')
fs.writeFileSync(swPath, bumped)
// ② 重新导航触发更新检查 → 新 SW 应停在 waiting(不打断当前页)
await page.goto('/', { waitUntil: 'domcontentloaded' })
await expect.poll(() => page.evaluate(() => navigator.serviceWorker.getRegistration()
.then((r) => !!(r && r.waiting))), { timeout: 25000 }).toBe(true)
// ③ 用户确认更新(等价于点「发现新版本,点击更新」)
await page.evaluate(() => navigator.serviceWorker.getRegistration().then((r) => {
if (r && r.waiting) r.waiting.postMessage({ type: 'SKIP_WAITING' })
}))
await page.reload({ waitUntil: 'domcontentloaded' })
// ④ 升级后页面正常渲染(不白屏)
await expect(page.locator('#root > *').first()).toBeVisible({ timeout: 20000 })
} finally {
fs.writeFileSync(swPath, original) // 无论成败都还原,避免污染其它 spec
}
})