import { describe, it, expect, vi, beforeEach } from 'vitest' import { EventEmitter } from 'node:events' vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } })) class FakeWebContents extends EventEmitter {} class FakeBrowserWindow extends EventEmitter { webContents = new FakeWebContents() show = vi.fn() focus = vi.fn() setAlwaysOnTop = vi.fn() loadURL = vi.fn() loadFile = vi.fn() close = vi.fn() destroyed = false isDestroyed(): boolean { return this.destroyed } } let lastWindow: FakeBrowserWindow | null = null function createBrowserWindow(): FakeBrowserWindow { const window = new FakeBrowserWindow() lastWindow = window return window } vi.mock('electron', () => ({ BrowserWindow: vi.fn(createBrowserWindow) })) const { openChatWindow, closeChatWindow, isChatWindowOpen, onChatWindowClosed } = await import('../../src/main/chatWindow') describe('chatWindow', () => { beforeEach(() => { lastWindow?.emit('closed') vi.clearAllMocks() lastWindow = null }) describe('openChatWindow()', () => { it('should create and load a window on the #chat hash', () => { openChatWindow() expect(lastWindow?.loadFile).toHaveBeenCalledWith( expect.stringContaining('index.html'), expect.objectContaining({ hash: 'chat' }) ) expect(isChatWindowOpen()).toBe(true) }) it('should reuse the existing window and bring it to front on a second call', () => { openChatWindow() const firstWindow = lastWindow openChatWindow() expect(lastWindow).toBe(firstWindow) expect(firstWindow?.show).toHaveBeenCalled() expect(firstWindow?.focus).toHaveBeenCalled() }) }) describe('closeChatWindow()', () => { it('should close the window when one is open', () => { openChatWindow() closeChatWindow() expect(lastWindow?.close).toHaveBeenCalled() }) it('should do nothing when no window is open', () => { expect(() => closeChatWindow()).not.toThrow() expect(isChatWindowOpen()).toBe(false) }) }) describe('onChatWindowClosed()', () => { it('should notify the registered callback when the window closes', () => { const callback = vi.fn() onChatWindowClosed(callback) openChatWindow() lastWindow?.emit('closed') expect(callback).toHaveBeenCalledOnce() expect(isChatWindowOpen()).toBe(false) }) }) })