Files
karaoke-gen/frontend/__tests__/version-check.test.ts
T
Andrew Beveridge ☄️andClaude Opus 4.8 eac3dac910 fix: recognize Turbopack chunk-load errors for post-deploy auto-reload (#879)
## Problem

Prod error-monitor alert:

```
Error: Failed to load chunk /_next/static/chunks/<ID>.js from module <NUM>
    at https://gen.nomadkaraoke.com/_next/static/chunks/turbopack-*.js
```

The gen frontend is a static export (`output: 'export'`) served from
GitHub Pages with hashed chunk filenames. On deploy, old chunk hashes
vanish, so a user with an already-loaded tab hits a **post-deploy
mismatch** when the app lazy-loads a stale chunk. The frontend is
designed to auto-recover from this via `hardReload()` in
`client-error-setup.ts` — but the recovery wasn't firing.

## Root cause

`isChunkLoadError()` in `frontend/lib/version-check.ts` only recognized
webpack/native-ESM phrasings (`ChunkLoadError`, `Loading chunk <id>
failed`, `Failed to fetch dynamically imported module`, `Importing a
module script failed`).

**Next.js 16 defaults to Turbopack**, whose browser runtime throws a
plain `Error` (name `"Error"`, *not* `ChunkLoadError`) with a different
message: `Failed to load chunk <path> from module <n>` (also `… as a
runtime dependency of chunk <id>` / `… from an HMR update`). Confirmed
by inspecting the built runtime
`out/_next/static/chunks/turbopack-*.js`.

None of the regexes matched → the auto-hard-reload never triggered (user
saw a broken page) **and** the error was reported to the monitor → this
alert.

## Fix

- Add `/Failed to load chunk/i` to `isChunkLoadError()`'s regex list,
documenting all three bundler families.
- Add the first tests for `isChunkLoadError` (webpack, Turbopack ×3
variants, native ESM, negatives).
- Bump `0.191.1` → `0.191.2`.

Left the crash-reporter's `isBenignError` untouched: a chunk error that
survives the 60s reload circuit-breaker *should* still be reported
(persistent = a real problem like missing CDN files, not mere
staleness).

## Notes

- Users who already saw the error recover with a manual reload — this
fix makes future post-deploy mismatches self-heal automatically.
- The error store aggregates by pattern and does not persist
`user_email`, so the affected visitor can't be identified (and this hit
was on the logged-out `/zh/` homepage anyway).

## Testing

- `npx jest __tests__/version-check.test.ts
__tests__/CrashReport.test.tsx` → 20/20 pass
- `npx eslint` on changed files → clean

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 12:01:24 -04:00

126 lines
3.9 KiB
TypeScript

/**
* @jest-environment jsdom
*/
import {
isStale,
hardReload,
isChunkLoadError,
__resetForTest,
__setBuildShaForTest,
} from '@/lib/version-check'
describe('version-check.isChunkLoadError', () => {
it('matches webpack ChunkLoadError by name', () => {
const e = new Error('boom')
e.name = 'ChunkLoadError'
expect(isChunkLoadError(e)).toBe(true)
})
it('matches webpack "Loading chunk <id> failed" message', () => {
expect(isChunkLoadError(new Error('Loading chunk 429 failed'))).toBe(true)
})
it.each([
// Turbopack (Next.js 16 default) — a plain Error, no ChunkLoadError name.
'Failed to load chunk /_next/static/chunks/e66613528f386db8.js from module 64893',
'Failed to load chunk /_next/static/chunks/abc.js as a runtime dependency of chunk 12',
'Failed to load chunk /_next/static/chunks/abc.js from an HMR update',
])('matches Turbopack chunk-load message: %s', (msg) => {
expect(isChunkLoadError(new Error(msg))).toBe(true)
})
it('matches native ESM dynamic-import failures', () => {
expect(
isChunkLoadError(new Error('Failed to fetch dynamically imported module: https://x/y.js')),
).toBe(true)
expect(isChunkLoadError(new Error('Importing a module script failed.'))).toBe(true)
})
it('ignores unrelated errors and falsy input', () => {
expect(isChunkLoadError(new Error('Cannot read properties of undefined'))).toBe(false)
expect(isChunkLoadError(null)).toBe(false)
expect(isChunkLoadError(undefined)).toBe(false)
})
})
describe('version-check.isStale', () => {
const fetchMock = jest.fn()
beforeEach(() => {
__resetForTest()
__setBuildShaForTest('aaa')
fetchMock.mockReset()
;(global as any).fetch = fetchMock
})
it('returns stale=false when SHAs match', async () => {
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ build_sha: 'aaa' }) })
const r = await isStale()
expect(r.stale).toBe(false)
expect(r.latestSha).toBe('aaa')
})
it('returns stale=true when SHAs differ', async () => {
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ build_sha: 'bbb' }) })
const r = await isStale()
expect(r.stale).toBe(true)
expect(r.latestSha).toBe('bbb')
})
it('fetches with cache: no-store', async () => {
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ build_sha: 'aaa' }) })
await isStale()
const [, init] = fetchMock.mock.calls[0]
expect(init.cache).toBe('no-store')
})
it('treats fetch failures as not-stale (fail-safe)', async () => {
fetchMock.mockRejectedValue(new Error('offline'))
const r = await isStale()
expect(r.stale).toBe(false)
})
it('treats "dev" build_sha as not-stale (local dev)', async () => {
__setBuildShaForTest('dev')
fetchMock.mockResolvedValue({ ok: true, json: async () => ({ build_sha: 'bbb' }) })
const r = await isStale()
expect(r.stale).toBe(false)
})
})
describe('version-check.hardReload circuit breaker', () => {
const assignMock = jest.fn()
let originalLocation: Location
beforeEach(() => {
__resetForTest()
assignMock.mockReset()
originalLocation = window.location
// @ts-expect-error — overwriting readonly for test
delete window.location
// @ts-expect-error — mock location
window.location = {
pathname: '/en/app/jobs/',
assign: assignMock,
reload: jest.fn(),
}
})
afterEach(() => {
// @ts-expect-error — restore
window.location = originalLocation
})
it('navigates with _v cache-buster on first call', () => {
hardReload('bbb')
expect(assignMock).toHaveBeenCalledTimes(1)
expect(assignMock.mock.calls[0][0]).toContain('_v=bbb')
expect(assignMock.mock.calls[0][0]).toContain('/en/app/jobs/')
})
it('refuses to reload twice within 60s (circuit breaker)', () => {
hardReload('bbb')
hardReload('ccc')
expect(assignMock).toHaveBeenCalledTimes(1)
})
})