mirror of
https://github.com/lobehub/lobehub.git
synced 2026-03-27 13:29:15 +07:00
✅ test(desktop): add unit tests for Core Browser module (#10535)
Add comprehensive unit tests for Desktop Core Browser: - Browser.ts (39 tests) - BrowserManager.ts (32 tests) Total: 71 tests (all passed) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
573
apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
Normal file
573
apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
Normal file
@@ -0,0 +1,573 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { App as AppCore } from '../../App';
|
||||
import Browser, { BrowserWindowOpts } from '../Browser';
|
||||
|
||||
// Use vi.hoisted to define mocks before hoisting
|
||||
const { mockBrowserWindow, mockNativeTheme, mockIpcMain, mockScreen, MockBrowserWindow } =
|
||||
vi.hoisted(() => {
|
||||
const mockBrowserWindow = {
|
||||
center: vi.fn(),
|
||||
close: vi.fn(),
|
||||
focus: vi.fn(),
|
||||
getBounds: vi.fn().mockReturnValue({ height: 600, width: 800, x: 0, y: 0 }),
|
||||
getContentBounds: vi.fn().mockReturnValue({ height: 600, width: 800 }),
|
||||
hide: vi.fn(),
|
||||
isDestroyed: vi.fn().mockReturnValue(false),
|
||||
isFocused: vi.fn().mockReturnValue(true),
|
||||
isFullScreen: vi.fn().mockReturnValue(false),
|
||||
isMaximized: vi.fn().mockReturnValue(false),
|
||||
isVisible: vi.fn().mockReturnValue(true),
|
||||
loadFile: vi.fn().mockResolvedValue(undefined),
|
||||
loadURL: vi.fn().mockResolvedValue(undefined),
|
||||
maximize: vi.fn(),
|
||||
minimize: vi.fn(),
|
||||
on: vi.fn(),
|
||||
once: vi.fn(),
|
||||
setBackgroundColor: vi.fn(),
|
||||
setBounds: vi.fn(),
|
||||
setFullScreen: vi.fn(),
|
||||
setPosition: vi.fn(),
|
||||
setTitleBarOverlay: vi.fn(),
|
||||
show: vi.fn(),
|
||||
unmaximize: vi.fn(),
|
||||
webContents: {
|
||||
openDevTools: vi.fn(),
|
||||
send: vi.fn(),
|
||||
session: {
|
||||
webRequest: {
|
||||
onHeadersReceived: vi.fn(),
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
MockBrowserWindow: vi.fn().mockImplementation(() => mockBrowserWindow),
|
||||
mockBrowserWindow,
|
||||
mockIpcMain: {
|
||||
handle: vi.fn(),
|
||||
removeHandler: vi.fn(),
|
||||
},
|
||||
mockNativeTheme: {
|
||||
off: vi.fn(),
|
||||
on: vi.fn(),
|
||||
shouldUseDarkColors: false,
|
||||
},
|
||||
mockScreen: {
|
||||
getDisplayNearestPoint: vi.fn().mockReturnValue({
|
||||
workArea: { height: 1080, width: 1920, x: 0, y: 0 },
|
||||
}),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// Mock electron
|
||||
vi.mock('electron', () => ({
|
||||
BrowserWindow: MockBrowserWindow,
|
||||
ipcMain: mockIpcMain,
|
||||
nativeTheme: mockNativeTheme,
|
||||
screen: mockScreen,
|
||||
}));
|
||||
|
||||
// Mock logger
|
||||
vi.mock('@/utils/logger', () => ({
|
||||
createLogger: () => ({
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock constants
|
||||
vi.mock('@/const/dir', () => ({
|
||||
buildDir: '/mock/build',
|
||||
preloadDir: '/mock/preload',
|
||||
resourcesDir: '/mock/resources',
|
||||
}));
|
||||
|
||||
vi.mock('@/const/env', () => ({
|
||||
isDev: false,
|
||||
isMac: false,
|
||||
isWindows: true,
|
||||
}));
|
||||
|
||||
vi.mock('@/const/theme', () => ({
|
||||
BACKGROUND_DARK: '#1a1a1a',
|
||||
BACKGROUND_LIGHT: '#ffffff',
|
||||
SYMBOL_COLOR_DARK: '#ffffff',
|
||||
SYMBOL_COLOR_LIGHT: '#000000',
|
||||
THEME_CHANGE_DELAY: 0,
|
||||
TITLE_BAR_HEIGHT: 32,
|
||||
}));
|
||||
|
||||
describe('Browser', () => {
|
||||
let browser: Browser;
|
||||
let mockApp: AppCore;
|
||||
let mockStoreManagerGet: ReturnType<typeof vi.fn>;
|
||||
let mockStoreManagerSet: ReturnType<typeof vi.fn>;
|
||||
let mockNextInterceptor: ReturnType<typeof vi.fn>;
|
||||
|
||||
const defaultOptions: BrowserWindowOpts = {
|
||||
height: 600,
|
||||
identifier: 'test-window',
|
||||
path: '/test',
|
||||
title: 'Test Window',
|
||||
width: 800,
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useFakeTimers();
|
||||
|
||||
// Reset mock behaviors
|
||||
mockBrowserWindow.isDestroyed.mockReturnValue(false);
|
||||
mockBrowserWindow.isVisible.mockReturnValue(true);
|
||||
mockBrowserWindow.isFocused.mockReturnValue(true);
|
||||
mockBrowserWindow.isFullScreen.mockReturnValue(false);
|
||||
mockBrowserWindow.loadURL.mockResolvedValue(undefined);
|
||||
mockBrowserWindow.loadFile.mockResolvedValue(undefined);
|
||||
mockNativeTheme.shouldUseDarkColors = false;
|
||||
|
||||
// Create mock App
|
||||
mockStoreManagerGet = vi.fn().mockReturnValue(undefined);
|
||||
mockStoreManagerSet = vi.fn();
|
||||
mockNextInterceptor = vi.fn().mockReturnValue(vi.fn());
|
||||
|
||||
mockApp = {
|
||||
browserManager: {
|
||||
retrieveByIdentifier: vi.fn(),
|
||||
},
|
||||
isQuiting: false,
|
||||
nextInterceptor: mockNextInterceptor,
|
||||
nextServerUrl: 'http://localhost:3000',
|
||||
storeManager: {
|
||||
get: mockStoreManagerGet,
|
||||
set: mockStoreManagerSet,
|
||||
},
|
||||
} as unknown as AppCore;
|
||||
|
||||
browser = new Browser(defaultOptions, mockApp);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('should set identifier and options', () => {
|
||||
expect(browser.identifier).toBe('test-window');
|
||||
expect(browser.options).toEqual(defaultOptions);
|
||||
});
|
||||
|
||||
it('should create BrowserWindow on construction', () => {
|
||||
expect(MockBrowserWindow).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should setup next interceptor', () => {
|
||||
expect(mockNextInterceptor).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('browserWindow getter', () => {
|
||||
it('should return existing window if not destroyed', () => {
|
||||
mockBrowserWindow.isDestroyed.mockReturnValue(false);
|
||||
|
||||
const win1 = browser.browserWindow;
|
||||
const win2 = browser.browserWindow;
|
||||
|
||||
// Should not create a new window
|
||||
expect(MockBrowserWindow).toHaveBeenCalledTimes(1);
|
||||
expect(win1).toBe(win2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('webContents getter', () => {
|
||||
it('should return webContents when window not destroyed', () => {
|
||||
mockBrowserWindow.isDestroyed.mockReturnValue(false);
|
||||
|
||||
expect(browser.webContents).toBe(mockBrowserWindow.webContents);
|
||||
});
|
||||
|
||||
it('should return null when window is destroyed', () => {
|
||||
mockBrowserWindow.isDestroyed.mockReturnValue(true);
|
||||
|
||||
expect(browser.webContents).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('retrieveOrInitialize', () => {
|
||||
it('should restore window size from store', () => {
|
||||
mockStoreManagerGet.mockImplementation((key: string) => {
|
||||
if (key === 'windowSize_test-window') {
|
||||
return { height: 700, width: 900 };
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
// Create new browser to trigger initialization with saved state
|
||||
const newBrowser = new Browser(defaultOptions, mockApp);
|
||||
|
||||
expect(MockBrowserWindow).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
height: 700,
|
||||
width: 900,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should use default size when no saved state', () => {
|
||||
mockStoreManagerGet.mockReturnValue(undefined);
|
||||
|
||||
expect(MockBrowserWindow).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
height: 600,
|
||||
width: 800,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should setup theme listener', () => {
|
||||
expect(mockNativeTheme.on).toHaveBeenCalledWith('updated', expect.any(Function));
|
||||
});
|
||||
|
||||
it('should setup CORS bypass', () => {
|
||||
expect(mockBrowserWindow.webContents.session.webRequest.onHeadersReceived).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should open devTools when devTools option is true', () => {
|
||||
const optionsWithDevTools: BrowserWindowOpts = {
|
||||
...defaultOptions,
|
||||
devTools: true,
|
||||
};
|
||||
|
||||
new Browser(optionsWithDevTools, mockApp);
|
||||
|
||||
expect(mockBrowserWindow.webContents.openDevTools).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('theme management', () => {
|
||||
describe('getPlatformThemeConfig', () => {
|
||||
it('should return Windows dark theme config', () => {
|
||||
mockNativeTheme.shouldUseDarkColors = true;
|
||||
|
||||
// Create browser with dark mode
|
||||
const darkBrowser = new Browser(defaultOptions, mockApp);
|
||||
|
||||
expect(MockBrowserWindow).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
backgroundColor: '#1a1a1a',
|
||||
titleBarOverlay: expect.objectContaining({
|
||||
color: '#1a1a1a',
|
||||
symbolColor: '#ffffff',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('should return Windows light theme config', () => {
|
||||
mockNativeTheme.shouldUseDarkColors = false;
|
||||
|
||||
expect(MockBrowserWindow).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
backgroundColor: '#ffffff',
|
||||
titleBarOverlay: expect.objectContaining({
|
||||
color: '#ffffff',
|
||||
symbolColor: '#000000',
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('handleThemeChange', () => {
|
||||
it('should reapply visual effects on theme change', () => {
|
||||
// Get the theme change handler
|
||||
const themeHandler = mockNativeTheme.on.mock.calls.find(
|
||||
(call) => call[0] === 'updated',
|
||||
)?.[1];
|
||||
|
||||
expect(themeHandler).toBeDefined();
|
||||
|
||||
// Trigger theme change
|
||||
themeHandler();
|
||||
vi.advanceTimersByTime(0);
|
||||
|
||||
// Should update window background and title bar
|
||||
expect(mockBrowserWindow.setBackgroundColor).toHaveBeenCalled();
|
||||
expect(mockBrowserWindow.setTitleBarOverlay).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('handleAppThemeChange', () => {
|
||||
it('should reapply visual effects', () => {
|
||||
browser.handleAppThemeChange();
|
||||
vi.advanceTimersByTime(0);
|
||||
|
||||
expect(mockBrowserWindow.setBackgroundColor).toHaveBeenCalled();
|
||||
expect(mockBrowserWindow.setTitleBarOverlay).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('isDarkMode', () => {
|
||||
it('should return true when themeMode is dark', () => {
|
||||
mockStoreManagerGet.mockImplementation((key: string) => {
|
||||
if (key === 'themeMode') return 'dark';
|
||||
return undefined;
|
||||
});
|
||||
|
||||
const darkBrowser = new Browser(defaultOptions, mockApp);
|
||||
// Access private getter through handleAppThemeChange which uses isDarkMode
|
||||
darkBrowser.handleAppThemeChange();
|
||||
vi.advanceTimersByTime(0);
|
||||
|
||||
expect(mockBrowserWindow.setBackgroundColor).toHaveBeenCalledWith('#1a1a1a');
|
||||
});
|
||||
|
||||
it('should use system theme when themeMode is auto', () => {
|
||||
mockStoreManagerGet.mockImplementation((key: string) => {
|
||||
if (key === 'themeMode') return 'auto';
|
||||
return undefined;
|
||||
});
|
||||
mockNativeTheme.shouldUseDarkColors = true;
|
||||
|
||||
const autoBrowser = new Browser(defaultOptions, mockApp);
|
||||
autoBrowser.handleAppThemeChange();
|
||||
vi.advanceTimersByTime(0);
|
||||
|
||||
expect(mockBrowserWindow.setBackgroundColor).toHaveBeenCalledWith('#1a1a1a');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadUrl', () => {
|
||||
it('should load full URL successfully', async () => {
|
||||
await browser.loadUrl('/test-path');
|
||||
|
||||
expect(mockBrowserWindow.loadURL).toHaveBeenCalledWith('http://localhost:3000/test-path');
|
||||
});
|
||||
|
||||
it('should load error page on failure', async () => {
|
||||
mockBrowserWindow.loadURL.mockRejectedValueOnce(new Error('Load failed'));
|
||||
|
||||
await browser.loadUrl('/test-path');
|
||||
|
||||
expect(mockBrowserWindow.loadFile).toHaveBeenCalledWith('/mock/resources/error.html');
|
||||
});
|
||||
|
||||
it('should setup retry handler on error', async () => {
|
||||
mockBrowserWindow.loadURL.mockRejectedValueOnce(new Error('Load failed'));
|
||||
|
||||
await browser.loadUrl('/test-path');
|
||||
|
||||
expect(mockIpcMain.removeHandler).toHaveBeenCalledWith('retry-connection');
|
||||
expect(mockIpcMain.handle).toHaveBeenCalledWith('retry-connection', expect.any(Function));
|
||||
});
|
||||
|
||||
it('should load fallback HTML when error page fails', async () => {
|
||||
mockBrowserWindow.loadURL.mockRejectedValueOnce(new Error('Load failed'));
|
||||
mockBrowserWindow.loadFile.mockRejectedValueOnce(new Error('Error page failed'));
|
||||
mockBrowserWindow.loadURL.mockResolvedValueOnce(undefined);
|
||||
|
||||
await browser.loadUrl('/test-path');
|
||||
|
||||
expect(mockBrowserWindow.loadURL).toHaveBeenCalledWith(
|
||||
expect.stringContaining('data:text/html'),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadPlaceholder', () => {
|
||||
it('should load splash screen', async () => {
|
||||
await browser.loadPlaceholder();
|
||||
|
||||
expect(mockBrowserWindow.loadFile).toHaveBeenCalledWith('/mock/resources/splash.html');
|
||||
});
|
||||
});
|
||||
|
||||
describe('window operations', () => {
|
||||
describe('show', () => {
|
||||
it('should show window', () => {
|
||||
browser.show();
|
||||
|
||||
expect(mockBrowserWindow.show).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('hide', () => {
|
||||
it('should hide window', () => {
|
||||
mockBrowserWindow.isFullScreen.mockReturnValue(false);
|
||||
|
||||
browser.hide();
|
||||
|
||||
expect(mockBrowserWindow.hide).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('close', () => {
|
||||
it('should close window', () => {
|
||||
browser.close();
|
||||
|
||||
expect(mockBrowserWindow.close).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('moveToCenter', () => {
|
||||
it('should center window', () => {
|
||||
browser.moveToCenter();
|
||||
|
||||
expect(mockBrowserWindow.center).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('setWindowSize', () => {
|
||||
it('should set window bounds', () => {
|
||||
browser.setWindowSize({ height: 700, width: 900 });
|
||||
|
||||
expect(mockBrowserWindow.setBounds).toHaveBeenCalledWith({
|
||||
height: 700,
|
||||
width: 900,
|
||||
});
|
||||
});
|
||||
|
||||
it('should use current size for missing dimensions', () => {
|
||||
mockBrowserWindow.getBounds.mockReturnValue({ height: 600, width: 800 });
|
||||
|
||||
browser.setWindowSize({ width: 900 });
|
||||
|
||||
expect(mockBrowserWindow.setBounds).toHaveBeenCalledWith({
|
||||
height: 600,
|
||||
width: 900,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('toggleVisible', () => {
|
||||
it('should hide when visible and focused', () => {
|
||||
mockBrowserWindow.isVisible.mockReturnValue(true);
|
||||
mockBrowserWindow.isFocused.mockReturnValue(true);
|
||||
|
||||
browser.toggleVisible();
|
||||
|
||||
expect(mockBrowserWindow.hide).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should show and focus when not visible', () => {
|
||||
mockBrowserWindow.isVisible.mockReturnValue(false);
|
||||
|
||||
browser.toggleVisible();
|
||||
|
||||
expect(mockBrowserWindow.show).toHaveBeenCalled();
|
||||
expect(mockBrowserWindow.focus).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should show and focus when visible but not focused', () => {
|
||||
mockBrowserWindow.isVisible.mockReturnValue(true);
|
||||
mockBrowserWindow.isFocused.mockReturnValue(false);
|
||||
|
||||
browser.toggleVisible();
|
||||
|
||||
expect(mockBrowserWindow.show).toHaveBeenCalled();
|
||||
expect(mockBrowserWindow.focus).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('broadcast', () => {
|
||||
it('should send message to webContents', () => {
|
||||
browser.broadcast('updateAvailable' as any, { version: '1.0.0' } as any);
|
||||
|
||||
expect(mockBrowserWindow.webContents.send).toHaveBeenCalledWith('updateAvailable', {
|
||||
version: '1.0.0',
|
||||
});
|
||||
});
|
||||
|
||||
it('should not send when window is destroyed', () => {
|
||||
mockBrowserWindow.isDestroyed.mockReturnValue(true);
|
||||
|
||||
browser.broadcast('updateAvailable' as any);
|
||||
|
||||
expect(mockBrowserWindow.webContents.send).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('destroy', () => {
|
||||
it('should cleanup theme listener', () => {
|
||||
browser.destroy();
|
||||
|
||||
expect(mockNativeTheme.off).toHaveBeenCalledWith('updated', expect.any(Function));
|
||||
});
|
||||
});
|
||||
|
||||
describe('close event handling', () => {
|
||||
let closeHandler: (e: any) => void;
|
||||
|
||||
beforeEach(() => {
|
||||
// Get the close handler registered during initialization
|
||||
closeHandler = mockBrowserWindow.on.mock.calls.find((call) => call[0] === 'close')?.[1];
|
||||
});
|
||||
|
||||
it('should save window size and allow close when app is quitting', () => {
|
||||
(mockApp as any).isQuiting = true;
|
||||
const mockEvent = { preventDefault: vi.fn() };
|
||||
|
||||
closeHandler(mockEvent);
|
||||
|
||||
expect(mockStoreManagerSet).toHaveBeenCalledWith('windowSize_test-window', {
|
||||
height: 600,
|
||||
width: 800,
|
||||
});
|
||||
expect(mockEvent.preventDefault).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should hide instead of close when keepAlive is true', () => {
|
||||
const keepAliveOptions: BrowserWindowOpts = {
|
||||
...defaultOptions,
|
||||
keepAlive: true,
|
||||
};
|
||||
const keepAliveBrowser = new Browser(keepAliveOptions, mockApp);
|
||||
|
||||
// Get the new close handler
|
||||
const keepAliveCloseHandler = mockBrowserWindow.on.mock.calls
|
||||
.filter((call) => call[0] === 'close')
|
||||
.pop()?.[1];
|
||||
|
||||
const mockEvent = { preventDefault: vi.fn() };
|
||||
keepAliveCloseHandler(mockEvent);
|
||||
|
||||
expect(mockEvent.preventDefault).toHaveBeenCalled();
|
||||
expect(mockBrowserWindow.hide).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should save size and allow close when keepAlive is false', () => {
|
||||
const mockEvent = { preventDefault: vi.fn() };
|
||||
|
||||
closeHandler(mockEvent);
|
||||
|
||||
expect(mockStoreManagerSet).toHaveBeenCalledWith('windowSize_test-window', {
|
||||
height: 600,
|
||||
width: 800,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('reapplyVisualEffects', () => {
|
||||
it('should apply visual effects', () => {
|
||||
browser.reapplyVisualEffects();
|
||||
|
||||
expect(mockBrowserWindow.setBackgroundColor).toHaveBeenCalled();
|
||||
expect(mockBrowserWindow.setTitleBarOverlay).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should not apply when window is destroyed', () => {
|
||||
mockBrowserWindow.isDestroyed.mockReturnValue(true);
|
||||
mockBrowserWindow.setBackgroundColor.mockClear();
|
||||
|
||||
browser.reapplyVisualEffects();
|
||||
|
||||
expect(mockBrowserWindow.setBackgroundColor).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,415 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import type { App as AppCore } from '../../App';
|
||||
import { BrowserManager } from '../BrowserManager';
|
||||
|
||||
// Use vi.hoisted to define mocks before hoisting
|
||||
const { MockBrowser, mockAppBrowsers, mockWindowTemplates } = vi.hoisted(() => {
|
||||
const createMockBrowserWindow = () => ({
|
||||
isMaximized: vi.fn().mockReturnValue(false),
|
||||
maximize: vi.fn(),
|
||||
minimize: vi.fn(),
|
||||
on: vi.fn(),
|
||||
unmaximize: vi.fn(),
|
||||
webContents: { id: Math.random() },
|
||||
});
|
||||
|
||||
const MockBrowser = vi.fn().mockImplementation((options: any) => {
|
||||
const browserWindow = createMockBrowserWindow();
|
||||
return {
|
||||
broadcast: vi.fn(),
|
||||
browserWindow,
|
||||
close: vi.fn(),
|
||||
handleAppThemeChange: vi.fn(),
|
||||
hide: vi.fn(),
|
||||
identifier: options.identifier,
|
||||
loadUrl: vi.fn().mockResolvedValue(undefined),
|
||||
options,
|
||||
show: vi.fn(),
|
||||
webContents: browserWindow.webContents,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
MockBrowser,
|
||||
mockAppBrowsers: {
|
||||
chat: {
|
||||
identifier: 'chat',
|
||||
keepAlive: true,
|
||||
path: '/chat',
|
||||
},
|
||||
settings: {
|
||||
identifier: 'settings',
|
||||
keepAlive: false,
|
||||
path: '/settings',
|
||||
},
|
||||
},
|
||||
mockWindowTemplates: {
|
||||
popup: {
|
||||
baseIdentifier: 'popup',
|
||||
height: 400,
|
||||
width: 600,
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// Mock Browser class
|
||||
vi.mock('../Browser', () => ({
|
||||
default: MockBrowser,
|
||||
}));
|
||||
|
||||
// Mock appBrowsers config
|
||||
vi.mock('../../../appBrowsers', () => ({
|
||||
appBrowsers: mockAppBrowsers,
|
||||
windowTemplates: mockWindowTemplates,
|
||||
}));
|
||||
|
||||
// Mock logger
|
||||
vi.mock('@/utils/logger', () => ({
|
||||
createLogger: () => ({
|
||||
debug: vi.fn(),
|
||||
error: vi.fn(),
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('BrowserManager', () => {
|
||||
let manager: BrowserManager;
|
||||
let mockApp: AppCore;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
// Reset MockBrowser
|
||||
MockBrowser.mockClear();
|
||||
|
||||
// Create mock App
|
||||
mockApp = {} as unknown as AppCore;
|
||||
|
||||
manager = new BrowserManager(mockApp);
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
it('should initialize with empty browsers Map', () => {
|
||||
expect(manager.browsers.size).toBe(0);
|
||||
});
|
||||
|
||||
it('should store app reference', () => {
|
||||
expect(manager.app).toBe(mockApp);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getMainWindow', () => {
|
||||
it('should return chat window', () => {
|
||||
const mainWindow = manager.getMainWindow();
|
||||
|
||||
expect(mainWindow.identifier).toBe('chat');
|
||||
});
|
||||
});
|
||||
|
||||
describe('showMainWindow', () => {
|
||||
it('should show the main window', () => {
|
||||
manager.showMainWindow();
|
||||
|
||||
const chatBrowser = manager.browsers.get('chat');
|
||||
expect(chatBrowser?.show).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('retrieveByIdentifier', () => {
|
||||
it('should return existing browser', () => {
|
||||
// First call creates the browser
|
||||
const browser1 = manager.retrieveByIdentifier('chat');
|
||||
// Second call should return same instance
|
||||
const browser2 = manager.retrieveByIdentifier('chat');
|
||||
|
||||
expect(browser1).toBe(browser2);
|
||||
expect(MockBrowser).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('should create static browser when not exists', () => {
|
||||
const browser = manager.retrieveByIdentifier('chat');
|
||||
|
||||
expect(MockBrowser).toHaveBeenCalledWith(mockAppBrowsers.chat, mockApp);
|
||||
expect(browser.identifier).toBe('chat');
|
||||
});
|
||||
|
||||
it('should throw error for non-static browser that does not exist', () => {
|
||||
expect(() => manager.retrieveByIdentifier('non-existent')).toThrow(
|
||||
'Browser non-existent not found and is not a static browser',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createMultiInstanceWindow', () => {
|
||||
it('should create window from template', () => {
|
||||
const result = manager.createMultiInstanceWindow('popup' as any, '/popup/path');
|
||||
|
||||
expect(result.browser).toBeDefined();
|
||||
expect(result.identifier).toMatch(/^popup_/);
|
||||
expect(MockBrowser).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
baseIdentifier: 'popup',
|
||||
height: 400,
|
||||
path: '/popup/path',
|
||||
width: 600,
|
||||
}),
|
||||
mockApp,
|
||||
);
|
||||
});
|
||||
|
||||
it('should use provided uniqueId', () => {
|
||||
const result = manager.createMultiInstanceWindow(
|
||||
'popup' as any,
|
||||
'/popup/path',
|
||||
'my-custom-id',
|
||||
);
|
||||
|
||||
expect(result.identifier).toBe('my-custom-id');
|
||||
});
|
||||
|
||||
it('should throw error for non-existent template', () => {
|
||||
expect(() => manager.createMultiInstanceWindow('nonexistent' as any, '/path')).toThrow(
|
||||
'Window template nonexistent not found',
|
||||
);
|
||||
});
|
||||
|
||||
it('should generate unique identifier when not provided', () => {
|
||||
const result1 = manager.createMultiInstanceWindow('popup' as any, '/path1');
|
||||
const result2 = manager.createMultiInstanceWindow('popup' as any, '/path2');
|
||||
|
||||
expect(result1.identifier).not.toBe(result2.identifier);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getWindowsByTemplate', () => {
|
||||
it('should return windows matching template prefix', () => {
|
||||
manager.createMultiInstanceWindow('popup' as any, '/path1', 'popup_1');
|
||||
manager.createMultiInstanceWindow('popup' as any, '/path2', 'popup_2');
|
||||
manager.retrieveByIdentifier('chat'); // This should not be included
|
||||
|
||||
const popupWindows = manager.getWindowsByTemplate('popup');
|
||||
|
||||
expect(popupWindows).toContain('popup_1');
|
||||
expect(popupWindows).toContain('popup_2');
|
||||
expect(popupWindows).not.toContain('chat');
|
||||
});
|
||||
|
||||
it('should return empty array when no matching windows', () => {
|
||||
const windows = manager.getWindowsByTemplate('nonexistent');
|
||||
|
||||
expect(windows).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('closeWindowsByTemplate', () => {
|
||||
it('should close all windows matching template', () => {
|
||||
const { browser: browser1 } = manager.createMultiInstanceWindow(
|
||||
'popup' as any,
|
||||
'/path1',
|
||||
'popup_1',
|
||||
);
|
||||
const { browser: browser2 } = manager.createMultiInstanceWindow(
|
||||
'popup' as any,
|
||||
'/path2',
|
||||
'popup_2',
|
||||
);
|
||||
|
||||
manager.closeWindowsByTemplate('popup');
|
||||
|
||||
expect(browser1.close).toHaveBeenCalled();
|
||||
expect(browser2.close).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('initializeBrowsers', () => {
|
||||
it('should initialize keepAlive browsers', () => {
|
||||
manager.initializeBrowsers();
|
||||
|
||||
// chat has keepAlive: true, settings has keepAlive: false
|
||||
expect(manager.browsers.has('chat')).toBe(true);
|
||||
expect(manager.browsers.has('settings')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('broadcastToAllWindows', () => {
|
||||
it('should broadcast to all browsers', () => {
|
||||
manager.retrieveByIdentifier('chat');
|
||||
manager.retrieveByIdentifier('settings');
|
||||
|
||||
manager.broadcastToAllWindows('updateAvailable' as any, { version: '1.0.0' } as any);
|
||||
|
||||
const chatBrowser = manager.browsers.get('chat');
|
||||
const settingsBrowser = manager.browsers.get('settings');
|
||||
|
||||
expect(chatBrowser?.broadcast).toHaveBeenCalledWith('updateAvailable', { version: '1.0.0' });
|
||||
expect(settingsBrowser?.broadcast).toHaveBeenCalledWith('updateAvailable', {
|
||||
version: '1.0.0',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('broadcastToWindow', () => {
|
||||
it('should broadcast to specific window', () => {
|
||||
manager.retrieveByIdentifier('chat');
|
||||
manager.retrieveByIdentifier('settings');
|
||||
|
||||
const chatBrowser = manager.browsers.get('chat');
|
||||
const settingsBrowser = manager.browsers.get('settings');
|
||||
|
||||
manager.broadcastToWindow('chat', 'updateAvailable' as any, { version: '1.0.0' } as any);
|
||||
|
||||
expect(chatBrowser?.broadcast).toHaveBeenCalledWith('updateAvailable', { version: '1.0.0' });
|
||||
expect(settingsBrowser?.broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should safely handle non-existent window', () => {
|
||||
expect(() =>
|
||||
manager.broadcastToWindow('nonexistent', 'updateAvailable' as any, {} as any),
|
||||
).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('redirectToPage', () => {
|
||||
it('should load URL and show window', async () => {
|
||||
const browser = await manager.redirectToPage('chat', 'agent');
|
||||
|
||||
expect(browser.hide).toHaveBeenCalled();
|
||||
expect(browser.loadUrl).toHaveBeenCalledWith('/chat/agent');
|
||||
expect(browser.show).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle subPath correctly', async () => {
|
||||
const browser = await manager.redirectToPage('chat', 'settings/profile');
|
||||
|
||||
expect(browser.loadUrl).toHaveBeenCalledWith('/chat/settings/profile');
|
||||
});
|
||||
|
||||
it('should handle search parameters', async () => {
|
||||
const browser = await manager.redirectToPage('chat', 'agent', 'id=123');
|
||||
|
||||
expect(browser.loadUrl).toHaveBeenCalledWith('/chat/agent?id=123');
|
||||
});
|
||||
|
||||
it('should handle search parameters starting with ?', async () => {
|
||||
const browser = await manager.redirectToPage('chat', undefined, '?id=123');
|
||||
|
||||
expect(browser.loadUrl).toHaveBeenCalledWith('/chat?id=123');
|
||||
});
|
||||
|
||||
it('should handle no subPath', async () => {
|
||||
const browser = await manager.redirectToPage('chat');
|
||||
|
||||
expect(browser.loadUrl).toHaveBeenCalledWith('/chat');
|
||||
});
|
||||
|
||||
it('should throw error on failure', async () => {
|
||||
const mockError = new Error('Load failed');
|
||||
MockBrowser.mockImplementationOnce((options: any) => ({
|
||||
broadcast: vi.fn(),
|
||||
browserWindow: { on: vi.fn(), webContents: { id: 1 } },
|
||||
close: vi.fn(),
|
||||
handleAppThemeChange: vi.fn(),
|
||||
hide: vi.fn(),
|
||||
identifier: options.identifier,
|
||||
loadUrl: vi.fn().mockRejectedValue(mockError),
|
||||
options: { path: '/chat' },
|
||||
show: vi.fn(),
|
||||
webContents: { id: 1 },
|
||||
}));
|
||||
|
||||
// Clear the browser cache
|
||||
manager.browsers.clear();
|
||||
|
||||
await expect(manager.redirectToPage('chat', 'agent')).rejects.toThrow('Load failed');
|
||||
});
|
||||
});
|
||||
|
||||
describe('window operations', () => {
|
||||
describe('closeWindow', () => {
|
||||
it('should close specified window', () => {
|
||||
manager.retrieveByIdentifier('chat');
|
||||
|
||||
manager.closeWindow('chat');
|
||||
|
||||
const browser = manager.browsers.get('chat');
|
||||
expect(browser?.close).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should safely handle non-existent window', () => {
|
||||
expect(() => manager.closeWindow('nonexistent')).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('minimizeWindow', () => {
|
||||
it('should minimize specified window', () => {
|
||||
manager.retrieveByIdentifier('chat');
|
||||
|
||||
manager.minimizeWindow('chat');
|
||||
|
||||
const browser = manager.browsers.get('chat');
|
||||
expect(browser?.browserWindow.minimize).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('maximizeWindow', () => {
|
||||
it('should maximize when not maximized', () => {
|
||||
manager.retrieveByIdentifier('chat');
|
||||
const browser = manager.browsers.get('chat');
|
||||
browser!.browserWindow.isMaximized = vi.fn().mockReturnValue(false);
|
||||
|
||||
manager.maximizeWindow('chat');
|
||||
|
||||
expect(browser?.browserWindow.maximize).toHaveBeenCalled();
|
||||
expect(browser?.browserWindow.unmaximize).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should unmaximize when already maximized', () => {
|
||||
manager.retrieveByIdentifier('chat');
|
||||
const browser = manager.browsers.get('chat');
|
||||
browser!.browserWindow.isMaximized = vi.fn().mockReturnValue(true);
|
||||
|
||||
manager.maximizeWindow('chat');
|
||||
|
||||
expect(browser?.browserWindow.unmaximize).toHaveBeenCalled();
|
||||
expect(browser?.browserWindow.maximize).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getIdentifierByWebContents', () => {
|
||||
it('should return identifier for known webContents', () => {
|
||||
const browser = manager.retrieveByIdentifier('chat');
|
||||
const webContents = browser.browserWindow.webContents;
|
||||
|
||||
const identifier = manager.getIdentifierByWebContents(webContents as any);
|
||||
|
||||
expect(identifier).toBe('chat');
|
||||
});
|
||||
|
||||
it('should return null for unknown webContents', () => {
|
||||
const unknownWebContents = { id: 999 };
|
||||
|
||||
const identifier = manager.getIdentifierByWebContents(unknownWebContents as any);
|
||||
|
||||
expect(identifier).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('handleAppThemeChange', () => {
|
||||
it('should notify all browsers of theme change', () => {
|
||||
manager.retrieveByIdentifier('chat');
|
||||
manager.retrieveByIdentifier('settings');
|
||||
|
||||
manager.handleAppThemeChange();
|
||||
|
||||
const chatBrowser = manager.browsers.get('chat');
|
||||
const settingsBrowser = manager.browsers.get('settings');
|
||||
|
||||
expect(chatBrowser?.handleAppThemeChange).toHaveBeenCalled();
|
||||
expect(settingsBrowser?.handleAppThemeChange).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user