eCourt-Doc-Edit/web/test/useVersionOpen.spec.ts
Suphonchai Phoonsawat e0558e3cf4 Hotfix: auto-download fallback when Word cold-start drops the open URL
ผู้ใช้จริง (Mac): กด "เปิดใน Word" ตอน Word ยังไม่เปิดค้างอยู่ — Word
cold-start แล้ว URL event หลุด แสดงหน้า Recent แทนเอกสาร (ข้อจำกัด
ms-word:ofe บน macOS; กลไกนี้ผ่าน manual test ตอน Word เปิดอยู่ก่อนแล้ว)

- useVersionOpen.openDocxUrl: หน้าต่างรอ 1.5s → 3s และเมื่อไม่เห็นการ
  สลับแอป → ดาวน์โหลดไฟล์ให้อัตโนมัติ (anchor → presigned attachment)
  + ข้อความแนะนำเปิดจาก Downloads หรือกดซ้ำเมื่อ Word เปิดอยู่แล้ว
  — ใช้ร่วมทุกจุดเปิด docx (version rows, v0, ไฟล์ร่าง) PDF ไม่เกี่ยว
- Tests: timing edge 2999/3000 + href + notice, ไม่ download เมื่อสลับ
  แอปจริง, re-click ยกเลิก timer เก่า (web 59/59 + build)
- Spec FR-15/16 (~3s + auto-download + หมายเหตุ cold-start) +
  acceptance-review เพิ่ม manual check item
- QA reviewer PASS (1 round; minors 3 — แก้ 1 ยอมรับ 2 พร้อมเหตุผล)

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-09-10 12:22:57 +07:00

157 lines
7.3 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createApp, type App } from 'vue'
import { useVersionOpen } from '../app/composables/useVersionOpen'
let app: App
let host: HTMLDivElement
const apiJson = vi.fn()
const replace = vi.fn()
const close = vi.fn()
let tab: { opener: unknown; closed: boolean; location: { replace: typeof replace }; close: typeof close }
function mount() {
let result!: ReturnType<typeof useVersionOpen>
host = document.createElement('div')
document.body.append(host)
app = createApp({ setup() { result = useVersionOpen(); return () => null } })
app.mount(host)
return result
}
beforeEach(() => {
vi.useFakeTimers()
vi.stubGlobal('useApi', () => ({ apiJson }))
tab = { opener: {}, closed: false, location: { replace }, close }
vi.spyOn(window, 'open').mockReturnValue(tab as unknown as Window)
})
afterEach(() => {
app?.unmount()
host?.remove()
vi.restoreAllMocks()
vi.unstubAllGlobals()
vi.clearAllMocks()
vi.useRealTimers()
})
describe('version open lifecycle', () => {
it('reserves PDF tab synchronously, navigates after auth, leaves completed PDF open on unmount', async () => {
let resolve!: (value: unknown) => void
apiJson.mockReturnValue(new Promise(r => { resolve = r }))
const state = mount()
const pending = state.openVersion('d', 'v', 'pdf')
expect(window.open).toHaveBeenCalledWith('about:blank', '_blank')
expect(tab.opener).toBeNull()
expect(state.openingVersionId.value).toBe('v')
resolve({ url: 'https://files.example/v.pdf' })
await pending
expect(replace).toHaveBeenCalledWith('https://files.example/v.pdf')
expect(state.fallbackUrl.value).toBe('https://files.example/v.pdf')
app.unmount()
expect(close).not.toHaveBeenCalled()
})
it('keeps a fallback when popup is blocked', async () => {
vi.mocked(window.open).mockReturnValue(null)
apiJson.mockResolvedValue({ url: 'https://files.example/v.pdf' })
const state = mount()
await state.openVersion('d', 'v', 'pdf')
expect(state.openNotice.value).toBeTruthy()
expect(state.fallbackUrl.value).toBe('https://files.example/v.pdf')
})
it('closes pending tab immediately on reset and ignores a late response', async () => {
let resolve!: (value: unknown) => void
apiJson.mockReturnValue(new Promise(r => { resolve = r }))
const state = mount()
const pending = state.openVersion('d', 'v', 'pdf')
state.resetOpen()
expect(close).toHaveBeenCalledTimes(1)
resolve({ url: 'https://files.example/v.pdf' })
await pending
expect(replace).not.toHaveBeenCalled()
expect(state.fallbackUrl.value).toBeNull()
})
it('closes reserved tab and reports request failure', async () => {
apiJson.mockRejectedValue(new Error('offline'))
const state = mount()
await state.openVersion('d', 'v', 'pdf')
expect(close).toHaveBeenCalled()
expect(state.downloadError.value).toBe('offline')
expect(state.openingVersionId.value).toBeNull()
})
it('handles synchronous popup errors and restores controls', async () => {
vi.mocked(window.open).mockImplementation(() => { throw new Error('popup error') })
const state = mount()
await state.openVersion('d', 'v', 'pdf')
expect(state.downloadError.value).toBe('popup error')
expect(state.openingVersionId.value).toBeNull()
})
it('offers Word fallback after timeout and removes listeners on unmount', async () => {
const assign = vi.spyOn(window.location, 'assign').mockImplementation(() => {})
const remove = vi.spyOn(window, 'removeEventListener')
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) // กัน auto-download click จริง
apiJson.mockResolvedValue({ url: 'https://files.example/v.docx?signature=a%2Fb' })
const state = mount()
await state.openVersion('d', 'v')
expect(assign).toHaveBeenCalledWith('ms-word:ofe|u|https://files.example/v.docx?signature=a%2Fb')
vi.advanceTimersByTime(3000)
expect(state.openNotice.value).toBeTruthy()
expect(state.fallbackUrl.value).toBeTruthy()
app.unmount()
expect(remove).toHaveBeenCalledWith('blur', expect.any(Function))
})
it('openDocxUrl opens a URL the caller already holds (ไฟล์ร่าง FR-16) without extra request', async () => {
const assign = vi.spyOn(window.location, 'assign').mockImplementation(() => {})
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
const state = mount()
state.openDocxUrl('https://files.example/draft.docx?sig=a%2Fb')
expect(apiJson).not.toHaveBeenCalled()
expect(assign).toHaveBeenCalledWith('ms-word:ofe|u|https://files.example/draft.docx?sig=a%2Fb')
expect(state.fallbackUrl.value).toBe('https://files.example/draft.docx?sig=a%2Fb')
vi.advanceTimersByTime(3000)
expect(state.openNotice.value).toBeTruthy()
})
it('auto-downloads the file to Downloads when Word did not take over within the wait window', () => {
const assign = vi.spyOn(window.location, 'assign').mockImplementation(() => {})
const saved: HTMLAnchorElement[] = []
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function clicked(this: HTMLAnchorElement) {
saved.push(this)
})
const state = mount()
state.openDocxUrl('https://files.example/draft.docx?sig=a%2Fb')
// ยังไม่มีอะไรเกิดก่อนหมดเวลารอ
vi.advanceTimersByTime(2999)
expect(saved).toHaveLength(0)
expect(state.openNotice.value).toBeNull()
// ครบหน้าต่างรอ (ไม่มีการ blur = Word ไม่ได้เปิด) → เซฟไฟล์ให้อัตโนมัติ + แจ้งเหตุผล
vi.advanceTimersByTime(1)
expect(saved).toHaveLength(1)
expect(saved[0].href).toBe('https://files.example/draft.docx?sig=a%2Fb')
expect(state.openNotice.value).toContain('Downloads')
})
it('does not auto-download when the app switch was detected (Word เปิดจริง)', async () => {
const assign = vi.spyOn(window.location, 'assign').mockImplementation(() => {})
const saved: HTMLAnchorElement[] = []
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function clicked(this: HTMLAnchorElement) {
saved.push(this)
})
const state = mount()
state.openDocxUrl('https://files.example/draft.docx?sig=a%2Fb')
window.dispatchEvent(new Event('blur')) // ผู้ใช้สลับไป Word
vi.advanceTimersByTime(3000)
expect(saved).toHaveLength(0)
expect(state.openNotice.value).toBeNull()
})
it('re-click cancels the pending auto-download — only the latest URL is saved once', () => {
const assign = vi.spyOn(window.location, 'assign').mockImplementation(() => {})
const saved: HTMLAnchorElement[] = []
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function clicked(this: HTMLAnchorElement) {
saved.push(this)
})
const state = mount()
state.openDocxUrl('https://files.example/first.docx')
vi.advanceTimersByTime(2000)
state.openDocxUrl('https://files.example/second.docx') // resetOpen ยกเลิก timer อันเก่า
vi.advanceTimersByTime(3000)
expect(saved).toHaveLength(1)
expect(saved[0].href).toBe('https://files.example/second.docx')
})
})