|
| 1 | +import { afterEach, describe, expect, it, vi } from 'vitest' |
| 2 | + |
| 3 | +const copyMock = vi.hoisted(() => vi.fn()) |
| 4 | +vi.mock('copy-to-clipboard', () => ({ default: copyMock })) |
| 5 | + |
| 6 | +import { writeClipboardText } from './clipboardWrite' |
| 7 | + |
| 8 | +// Regression: over plain http on another device (the remote server |
| 9 | +// instance) navigator.clipboard does not exist, and the old direct |
| 10 | +// writeText calls silently dropped every copy action. |
| 11 | +describe('writeClipboardText', () => { |
| 12 | + afterEach(() => { |
| 13 | + vi.unstubAllGlobals() |
| 14 | + copyMock.mockReset() |
| 15 | + }) |
| 16 | + |
| 17 | + it('uses navigator.clipboard when available', async () => { |
| 18 | + const writeText = vi.fn().mockResolvedValue(undefined) |
| 19 | + vi.stubGlobal('navigator', { clipboard: { writeText } }) |
| 20 | + await writeClipboardText('hello') |
| 21 | + expect(writeText).toHaveBeenCalledWith('hello') |
| 22 | + expect(copyMock).not.toHaveBeenCalled() |
| 23 | + }) |
| 24 | + |
| 25 | + it('falls back to the execCommand path when navigator.clipboard is absent', async () => { |
| 26 | + vi.stubGlobal('navigator', {}) |
| 27 | + copyMock.mockReturnValue(true) |
| 28 | + await writeClipboardText('hello') |
| 29 | + expect(copyMock).toHaveBeenCalledWith('hello') |
| 30 | + }) |
| 31 | + |
| 32 | + it('falls back when the clipboard API rejects (permission denied)', async () => { |
| 33 | + const writeText = vi.fn().mockRejectedValue(new Error('denied')) |
| 34 | + vi.stubGlobal('navigator', { clipboard: { writeText } }) |
| 35 | + copyMock.mockReturnValue(true) |
| 36 | + await writeClipboardText('hello') |
| 37 | + expect(copyMock).toHaveBeenCalledWith('hello') |
| 38 | + }) |
| 39 | + |
| 40 | + it('throws when both doors fail, so callers surface real feedback', async () => { |
| 41 | + vi.stubGlobal('navigator', {}) |
| 42 | + copyMock.mockReturnValue(false) |
| 43 | + await expect(writeClipboardText('hello')).rejects.toThrow(/Copy failed/) |
| 44 | + }) |
| 45 | +}) |
0 commit comments