|
| 1 | +/** |
| 2 | + * @vitest-environment jsdom |
| 3 | + */ |
| 4 | +import { act } from 'react' |
| 5 | +import { createRoot, type Root } from 'react-dom/client' |
| 6 | +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' |
| 7 | +import { MothershipHandoffStorage } from '@/lib/core/utils/browser-storage' |
| 8 | +import { useMothershipHandoff } from '@/app/workspace/[workspaceId]/home/hooks/use-mothership-handoff' |
| 9 | + |
| 10 | +const { mockQueryState } = vi.hoisted(() => ({ |
| 11 | + mockQueryState: { |
| 12 | + value: null as string | null, |
| 13 | + setValue: vi.fn(), |
| 14 | + }, |
| 15 | +})) |
| 16 | + |
| 17 | +vi.mock('nuqs', () => ({ |
| 18 | + useQueryState: () => [mockQueryState.value, mockQueryState.setValue], |
| 19 | +})) |
| 20 | + |
| 21 | +const mockSendMessage = vi.fn(async () => {}) |
| 22 | + |
| 23 | +function TestHarness({ renderKey }: { renderKey: number }) { |
| 24 | + useMothershipHandoff({ |
| 25 | + workspaceId: 'workspace-1', |
| 26 | + sendMessage: mockSendMessage, |
| 27 | + }) |
| 28 | + return <span>{renderKey}</span> |
| 29 | +} |
| 30 | + |
| 31 | +describe('useMothershipHandoff', () => { |
| 32 | + let container: HTMLDivElement |
| 33 | + let root: Root |
| 34 | + |
| 35 | + beforeEach(() => { |
| 36 | + ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true |
| 37 | + localStorage.clear() |
| 38 | + mockQueryState.value = null |
| 39 | + mockQueryState.setValue.mockClear() |
| 40 | + mockSendMessage.mockClear() |
| 41 | + container = document.createElement('div') |
| 42 | + document.body.appendChild(container) |
| 43 | + root = createRoot(container) |
| 44 | + }) |
| 45 | + |
| 46 | + afterEach(() => { |
| 47 | + act(() => root.unmount()) |
| 48 | + container.remove() |
| 49 | + }) |
| 50 | + |
| 51 | + it('consumes a handoff on the initial Home mount', async () => { |
| 52 | + MothershipHandoffStorage.store({ message: 'initial prompt' }, 'workspace-1') |
| 53 | + |
| 54 | + await act(async () => { |
| 55 | + root.render(<TestHarness renderKey={0} />) |
| 56 | + }) |
| 57 | + |
| 58 | + expect(mockSendMessage).toHaveBeenCalledWith('initial prompt', undefined, undefined) |
| 59 | + }) |
| 60 | + |
| 61 | + it('consumes a handoff when a cached Home route receives the URL signal', async () => { |
| 62 | + await act(async () => { |
| 63 | + root.render(<TestHarness renderKey={0} />) |
| 64 | + }) |
| 65 | + MothershipHandoffStorage.store({ message: 'cached route prompt' }, 'workspace-1') |
| 66 | + mockQueryState.value = '1' |
| 67 | + |
| 68 | + await act(async () => { |
| 69 | + root.render(<TestHarness renderKey={1} />) |
| 70 | + }) |
| 71 | + |
| 72 | + expect(mockSendMessage).toHaveBeenCalledWith('cached route prompt', undefined, undefined) |
| 73 | + expect(mockQueryState.setValue).toHaveBeenCalledWith(null) |
| 74 | + }) |
| 75 | +}) |
0 commit comments