import assert from 'node:assert/strict' import test from 'node:test' import { CHUNK_RELOAD_GUARD_MS, isChunkLoadError, shouldAutoReloadChunkFailure, } from '../src/utils/chunk-load-error.ts' function createStorage(initial: Record = {}) { const values = new Map(Object.entries(initial)) return { getItem(key: string) { return values.get(key) ?? null }, setItem(key: string, value: string) { values.set(key, String(value)) }, } } test('识别浏览器动态 import 失败文案', () => { assert.equal( isChunkLoadError( new TypeError( 'Failed to fetch dynamically imported module: https://worker.khhao.com/assets/WorkerConsignmentPage-abc.js', ), ), true, ) assert.equal(isChunkLoadError(new Error('Importing a module script failed.')), true) assert.equal(isChunkLoadError(new Error('Load failed')), true) assert.equal( isChunkLoadError({ name: 'ChunkLoadError', message: 'Loading chunk 12 failed' }), true, ) }) test('不把普通业务错误当成分片失败', () => { assert.equal(isChunkLoadError(new Error('接口请求失败')), false) assert.equal(isChunkLoadError(null), false) assert.equal(isChunkLoadError(undefined), false) }) test('首次分片失败允许自动刷新,窗口内再次失败不再刷新', () => { const storage = createStorage() const now = 1_700_000_000_000 assert.equal(shouldAutoReloadChunkFailure(storage, now), true) assert.equal(shouldAutoReloadChunkFailure(storage, now + 1_000), false) assert.equal(shouldAutoReloadChunkFailure(storage, now + CHUNK_RELOAD_GUARD_MS - 1), false) }) test('超过防抖窗口后允许再次自动刷新', () => { const storage = createStorage() const now = 1_700_000_000_000 assert.equal(shouldAutoReloadChunkFailure(storage, now), true) assert.equal(shouldAutoReloadChunkFailure(storage, now + CHUNK_RELOAD_GUARD_MS), true) }) test('存储不可用时不做自动刷新,避免无限循环', () => { const storage = { getItem() { throw new Error('denied') }, setItem() { throw new Error('denied') }, } assert.equal(shouldAutoReloadChunkFailure(storage), false) assert.equal(shouldAutoReloadChunkFailure(null), false) })