fix(web): harden clipboard copy and terminal paste flows (#187)

This commit is contained in:
gaius-codius
2026-02-19 08:08:52 +08:00
committed by GitHub
parent c8682047bf
commit 77cfa715f9
7 changed files with 367 additions and 10 deletions
+56
View File
@@ -0,0 +1,56 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { safeCopyToClipboard } from './clipboard'
describe('safeCopyToClipboard', () => {
beforeEach(() => {
vi.restoreAllMocks()
Object.defineProperty(document, 'execCommand', {
configurable: true,
writable: true,
value: vi.fn(() => false)
})
})
it('uses navigator clipboard writeText when available', async () => {
const writeText = vi.fn(async () => {})
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText }
})
const execCommand = vi.mocked(document.execCommand)
execCommand.mockReturnValue(true)
await safeCopyToClipboard('hello')
expect(writeText).toHaveBeenCalledWith('hello')
expect(execCommand).not.toHaveBeenCalled()
})
it('falls back to execCommand when clipboard api write fails', async () => {
const writeText = vi.fn(async () => {
throw new Error('clipboard denied')
})
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: { writeText }
})
const execCommand = vi.mocked(document.execCommand)
execCommand.mockReturnValue(true)
await safeCopyToClipboard('fallback')
expect(writeText).toHaveBeenCalledWith('fallback')
expect(execCommand).toHaveBeenCalledWith('copy')
})
it('throws when both modern and legacy copy strategies fail', async () => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: undefined
})
const execCommand = vi.mocked(document.execCommand)
execCommand.mockReturnValue(false)
await expect(safeCopyToClipboard('x')).rejects.toThrow('Copy to clipboard failed')
})
})