import { describe, test, expect, afterEach, vi } from 'vitest'; import React from 'react'; import { createRoot, Root } from 'react-dom/client'; import { act } from 'react-dom/test-utils'; import { DeviceProvider, useDevice } from './DeviceContext'; import type { DeviceMode } from '../types'; let container: HTMLDivElement; let root: Root; let api: ReturnType; const Probe: React.FC = () => { api = useDevice(); return {api.device}; }; function mount(ui: React.ReactElement) { container = document.createElement('div'); document.body.appendChild(container); act(() => { root = createRoot(container); root.render(ui); }); } const shown = () => container.querySelector('[data-testid="device"]')!.textContent; function stubMatchMedia(matches: boolean) { vi.stubGlobal('matchMedia', (q: string) => ({ matches, media: q, onchange: null, addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {}, dispatchEvent: () => false, })); } afterEach(() => { act(() => root.unmount()); container.remove(); vi.unstubAllGlobals(); }); describe('DeviceContext', () => { test('without a provider: desktop + a no-op setter', () => { mount(); expect(shown()).toBe('desktop'); act(() => api.setDevice('mobile')); expect(shown()).toBe('desktop'); }); test('provider defaults to desktop on a desktop viewport', () => { stubMatchMedia(false); mount(); expect(shown()).toBe('desktop'); }); test('setDevice propagates to every consumer', () => { stubMatchMedia(false); const Other: React.FC = () => {useDevice().device}; mount(); act(() => api.setDevice('tablet')); expect(shown()).toBe('tablet'); expect(container.querySelector('[data-testid="other"]')!.textContent).toBe('tablet'); }); test('a mobile viewport forces the mobile canvas once, then respects the user choice', () => { stubMatchMedia(true); mount(); expect(shown()).toBe('mobile'); act(() => api.setDevice('desktop')); expect(shown()).toBe('desktop'); }); test('initialDevice seeds the state', () => { stubMatchMedia(false); mount(); expect(shown()).toBe('tablet'); }); });