Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✅ test: sweep per-file UI mocks, lift shared mocks to global setup, prebundle @lobehub/ui (#18761)

Innei431f6371afe5
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index a985d398c49..0967ef424bc 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -1,12 +1 @@
-{
- "src/features/Conversation/Error/index.test.tsx": {
- "no-restricted-imports": {
- "count": 1
- }
- },
- "src/store/chat/slices/message/action.test.ts": {
- "no-restricted-imports": {
- "count": 1
- }
- }
-}
+{}
diff --git a/packages/builtin-tool-task/src/client/Render/index.test.tsx b/packages/builtin-tool-task/src/client/Render/index.test.tsx
index bd7f5ce5a9e..cfc2f25ff17 100644
--- a/packages/builtin-tool-task/src/client/Render/index.test.tsx
+++ b/packages/builtin-tool-task/src/client/Render/index.test.tsx
@@ -24,20 +24,15 @@ vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key.split('.').at(-1) || key }),
}));
-// Headless stubs for @lobehub/ui so we exercise our own markup, not the design
-// system internals (which would need a theme provider in jsdom).
-vi.mock('@lobehub/ui', () => ({
- ActionIcon: ({ title }: { title?: string }) => <button data-testid="action-icon" title={title} />,
- Block: ({ children, onClick }: { children?: ReactNode; onClick?: () => void }) => (
- <div data-testid="block" onClick={onClick}>
+// base-ui Button requires the app-level motion provider (this package has no
+// shared vitest setup, unlike src tests which stub it globally).
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ Button: ({ children, ...props }: { children?: ReactNode }) => (
+ <button type="button" {...props}>
{children}
- </div>
+ </button>
),
- Icon: () => <span data-testid="icon" />,
- Markdown: ({ children }: { children?: ReactNode }) => (
- <div data-testid="markdown">{children}</div>
- ),
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
}));
vi.mock('@/features/AgentTasks/features/AssigneeAvatar', () => ({
@@ -111,7 +106,7 @@ describe('EditTaskRender', () => {
it('renders the instruction preview as markdown', () => {
renderEdit({ instruction: '# Do the thing' });
- expect(screen.getByTestId('markdown').textContent).toContain('# Do the thing');
+ expect(screen.getByRole('heading', { name: 'Do the thing' })).toBeTruthy();
});
it('renders dependency changes', () => {
@@ -125,7 +120,7 @@ describe('EditTaskRender', () => {
renderEdit({});
expect(screen.getByText('T-1')).toBeTruthy();
- expect(screen.queryByTestId('markdown')).toBeNull();
+ expect(screen.queryByRole('heading')).toBeNull();
expect(screen.queryByTestId('assignee-avatar')).toBeNull();
});
});
@@ -166,7 +161,7 @@ describe('SetTaskVerifyRender', () => {
});
// Body is just the requirement markdown — verifier / iterations are not shown.
- expect(screen.getByTestId('markdown').textContent).toContain('## Acceptance');
+ expect(screen.getByRole('heading', { name: 'Acceptance' })).toBeTruthy();
expect(screen.queryByTestId('assignee-avatar')).toBeNull();
expect(screen.queryByText('3')).toBeNull();
});
diff --git a/packages/builtin-tool-task/vitest.config.mts b/packages/builtin-tool-task/vitest.config.mts
index cb722729b0a..4f1dbb49472 100644
--- a/packages/builtin-tool-task/vitest.config.mts
+++ b/packages/builtin-tool-task/vitest.config.mts
@@ -1,18 +1,35 @@
-import { dirname, resolve } from 'node:path';
+import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vitest/config';
-const packageDir = dirname(fileURLToPath(import.meta.url));
-const repoRoot = resolve(packageDir, '../..');
+const packageDir = path.dirname(fileURLToPath(import.meta.url));
+const repoRoot = path.resolve(packageDir, '../..');
export default defineConfig({
+ plugins: [
+ {
+ enforce: 'pre',
+ name: 'stub-lobehub-ui-motion-provider',
+ resolveId(id, importer) {
+ if (!importer || !importer.includes('/@lobehub/ui/')) return null;
+ if (/MotionProvider(?:\/index(?:\.(?:mjs|js|tsx))?)?$/.test(id))
+ return path.resolve(repoRoot, 'tests/mocks/lobehubUiMotionProvider.tsx');
+ return null;
+ },
+ },
+ ],
resolve: {
alias: {
- '@': resolve(repoRoot, 'src'),
+ '@': path.resolve(repoRoot, 'src'),
},
},
test: {
environment: 'happy-dom',
+ server: {
+ deps: {
+ inline: [/@lobehub\//],
+ },
+ },
},
});
diff --git a/packages/builtin-tool-user-interaction/src/client/Inspector/AskUserQuestion/index.test.tsx b/packages/builtin-tool-user-interaction/src/client/Inspector/AskUserQuestion/index.test.tsx
index 842da927d46..119a246736a 100644
--- a/packages/builtin-tool-user-interaction/src/client/Inspector/AskUserQuestion/index.test.tsx
+++ b/packages/builtin-tool-user-interaction/src/client/Inspector/AskUserQuestion/index.test.tsx
@@ -19,10 +19,7 @@ vi.mock('@lobechat/shared-tool-ui/styles', () => ({
vi.mock('@lobehub/ui', () => ({}));
-vi.mock('antd-style', () => ({
- createStaticStyles: () => new Proxy({}, { get: (_target, property) => String(property) }),
- cx: (...classNames: Array<string | false | undefined>) => classNames.filter(Boolean).join(' '),
-}));
+vi.mock('@lobehub/ui/base-ui', () => ({}));
describe('AskUserQuestionInspector', () => {
afterEach(cleanup);
diff --git a/packages/builtin-tools/src/codex/ErrorInspector.test.tsx b/packages/builtin-tools/src/codex/ErrorInspector.test.tsx
index 514b246b5cb..dafaa470677 100644
--- a/packages/builtin-tools/src/codex/ErrorInspector.test.tsx
+++ b/packages/builtin-tools/src/codex/ErrorInspector.test.tsx
@@ -17,22 +17,11 @@ vi.mock('@lobechat/shared-tool-ui/styles', () => ({
shinyTextStyles: { shinyText: 'shiny-text' },
}));
-vi.mock('@lobehub/ui', () => ({
- Icon: ({ className }: { className?: string }) => (
- <span className={className} data-testid="icon" />
- ),
-}));
-
-vi.mock('antd-style', () => ({
- createStaticStyles: () => new Proxy({}, { get: (_target, property) => String(property) }),
- cx: (...classNames: Array<string | false | undefined>) => classNames.filter(Boolean).join(' '),
-}));
-
describe('Codex ErrorInspector', () => {
afterEach(cleanup);
it('renders the warning icon and error message', () => {
- render(
+ const { container } = render(
<ErrorInspector
apiName="error"
args={{ id: 'item_0', message: 'The session model changed.', type: 'error' }}
@@ -40,7 +29,7 @@ describe('Codex ErrorInspector', () => {
/>,
);
- expect(screen.getByTestId('icon')).toBeTruthy();
+ expect(container.querySelector('svg')).toBeTruthy();
expect(screen.getByText('The session model changed.')).toBeTruthy();
});
diff --git a/packages/builtin-tools/vitest.config.mts b/packages/builtin-tools/vitest.config.mts
index 4ac6027d578..b618dfb336c 100644
--- a/packages/builtin-tools/vitest.config.mts
+++ b/packages/builtin-tools/vitest.config.mts
@@ -3,5 +3,10 @@ import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
environment: 'node',
+ server: {
+ deps: {
+ inline: [/@lobehub\//],
+ },
+ },
},
});
diff --git a/src/components/AntdStaticMethods/index.test.tsx b/src/components/AntdStaticMethods/index.test.tsx
index 207387c1946..a32a3dc22c6 100644
--- a/src/components/AntdStaticMethods/index.test.tsx
+++ b/src/components/AntdStaticMethods/index.test.tsx
@@ -11,7 +11,8 @@ const mockUseApp = {
notification: { open: vi.fn() },
};
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: vi.fn(() => mockUseApp),
},
diff --git a/src/components/AsyncBoundary/index.test.tsx b/src/components/AsyncBoundary/index.test.tsx
index 30515562ffb..320c0760a76 100644
--- a/src/components/AsyncBoundary/index.test.tsx
+++ b/src/components/AsyncBoundary/index.test.tsx
@@ -3,15 +3,6 @@ import { describe, expect, it, vi } from 'vitest';
import AsyncBoundary from './index';
-// Stub the base-ui Button (the failure state's Retry) to a native button — it
-// needs a MotionProvider the app sets up globally but the unit env doesn't; the
-// state-machine assertions only care that a button is/isn't present. vitest
-// hoists this above the imports regardless of position.
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: ({ children, onClick }: any) => <button onClick={onClick}>{children}</button>,
- Text: ({ children }: any) => <span>{children}</span>,
-}));
-
const DATA = <div>DATA_CONTENT</div>;
const EMPTY = <div>EMPTY_ONBOARDING</div>;
const LOADING = <div>LOADING_SKELETON</div>;
diff --git a/src/components/DragUpload/useDragUpload.test.tsx b/src/components/DragUpload/useDragUpload.test.tsx
index 5ac532cd326..e948782b48f 100644
--- a/src/components/DragUpload/useDragUpload.test.tsx
+++ b/src/components/DragUpload/useDragUpload.test.tsx
@@ -12,9 +12,10 @@ import { getContainer, useDragUpload } from './useDragUpload';
// Mock the hooks and components
vi.mock('@/hooks/useMediaUploadAbility');
vi.mock('@/store/agent');
-vi.mock('@lobehub/ui/base-ui', () => {
- return { toast: { warning: vi.fn() } };
-});
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
+}));
describe('useDragUpload', () => {
let mockOnUploadFiles: Mock;
diff --git a/src/components/Error/remoteServerErrorToast.test.ts b/src/components/Error/remoteServerErrorToast.test.ts
index a5993c7027c..42385b34fbd 100644
--- a/src/components/Error/remoteServerErrorToast.test.ts
+++ b/src/components/Error/remoteServerErrorToast.test.ts
@@ -4,7 +4,8 @@ import { remoteServerErrorToast } from './remoteServerErrorToast';
const toastError = vi.fn();
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
toast: { error: (...args: unknown[]) => toastError(...args) },
}));
diff --git a/src/components/StatisticCard/index.test.tsx b/src/components/StatisticCard/index.test.tsx
index 7925bbebbb0..4c0c2239c01 100644
--- a/src/components/StatisticCard/index.test.tsx
+++ b/src/components/StatisticCard/index.test.tsx
@@ -1,46 +1,29 @@
+import type { BlockProps } from '@lobehub/ui';
import { render, screen } from '@testing-library/react';
-import { type ComponentProps, type ReactNode } from 'react';
-import { describe, expect, it, vi } from 'vitest';
+import type { ComponentType } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import StatisticCard from './index';
+const blockPropsSpy = vi.hoisted(() => vi.fn());
+
vi.mock('@lobehub/ui', async (importOriginal) => {
const actual = await importOriginal<Record<string, unknown>>();
+ const ActualBlock = actual.Block as ComponentType<BlockProps>;
return {
...actual,
- Block: ({
- children,
- className,
- padding,
- paddingBlock,
- paddingInline,
- style,
- variant,
- }: {
- children?: ReactNode;
- className?: string;
- padding?: number | string;
- paddingBlock?: number | string;
- paddingInline?: number | string;
- style?: ComponentProps<'div'>['style'];
- variant?: string;
- }) => (
- <div
- className={className}
- data-padding={padding}
- data-padding-block={paddingBlock}
- data-padding-inline={paddingInline}
- data-testid="block"
- data-variant={variant}
- style={style}
- >
- {children}
- </div>
- ),
+ Block: (props: BlockProps) => {
+ blockPropsSpy(props);
+ return <ActualBlock {...props} />;
+ },
};
});
describe('StatisticCard', () => {
+ beforeEach(() => {
+ blockPropsSpy.mockClear();
+ });
+
it('renders title and formatted value with prefix, suffix and precision', () => {
render(
<StatisticCard
@@ -115,16 +98,19 @@ describe('StatisticCard', () => {
/>,
);
- const block = screen.getByTestId('block');
- expect(block).toHaveAttribute('data-variant', 'outlined');
- expect(block).toHaveAttribute('data-padding', '24');
- expect(block).toHaveAttribute('data-padding-block', '8');
- expect(block).toHaveAttribute('data-padding-inline', '16');
+ expect(blockPropsSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ padding: 24,
+ paddingBlock: 8,
+ paddingInline: 16,
+ variant: 'outlined',
+ }),
+ );
});
it('defaults to the borderless variant', () => {
render(<StatisticCard title="T" />);
- expect(screen.getByTestId('block')).toHaveAttribute('data-variant', 'borderless');
+ expect(blockPropsSpy).toHaveBeenCalledWith(expect.objectContaining({ variant: 'borderless' }));
});
});
diff --git a/src/features/Acceptance/CriterionList/CriterionEditModal.test.ts b/src/features/Acceptance/CriterionList/CriterionEditModal.test.ts
index 35e5c4dd63b..0b309136feb 100644
--- a/src/features/Acceptance/CriterionList/CriterionEditModal.test.ts
+++ b/src/features/Acceptance/CriterionList/CriterionEditModal.test.ts
@@ -11,16 +11,9 @@ vi.mock('@lobehub/ui', () => ({
TextArea: () => null,
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: () => null,
- Select: () => null,
- Switch: () => null,
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
createModal: mocks.createModal,
- useModalContext: () => ({ close: vi.fn() }),
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
}));
describe('openCriterionEditModal', () => {
diff --git a/src/features/Acceptance/Viewer/TopicPanel.test.ts b/src/features/Acceptance/Viewer/TopicPanel.test.ts
index 7ff2a5376af..5e2c1005214 100644
--- a/src/features/Acceptance/Viewer/TopicPanel.test.ts
+++ b/src/features/Acceptance/Viewer/TopicPanel.test.ts
@@ -2,20 +2,17 @@
* @vitest-environment happy-dom
*/
import { fireEvent, render } from '@testing-library/react';
-import { createElement, type ReactNode } from 'react';
+import { createElement } from 'react';
import { describe, expect, it, vi } from 'vitest';
import TopicPanel from './TopicPanel';
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children?: ReactNode }) => createElement('div', null, children),
- Icon: () => null,
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
+// Real base-ui ActionIcon only surfaces its title via a hover Tooltip, so the
+// static DOM has no accessible name to query.
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) =>
createElement('button', { onClick, title }, title),
- Text: ({ children }: { children?: ReactNode }) => createElement('span', null, children),
}));
vi.mock('@/features/AgentTasks/AgentTaskDetail/TopicChatDrawer', () => ({
@@ -41,10 +38,6 @@ vi.mock('@/features/AgentTasks/AgentTaskDetail/TopicChatDrawer', () => ({
),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
describe('TopicPanel', () => {
it('renders the topic conversation in the right rail and returns to runs', () => {
const onBack = vi.fn();
diff --git a/src/features/Acceptance/Viewer/attachments.test.tsx b/src/features/Acceptance/Viewer/attachments.test.tsx
index c2d7f94606c..27cdea49744 100644
--- a/src/features/Acceptance/Viewer/attachments.test.tsx
+++ b/src/features/Acceptance/Viewer/attachments.test.tsx
@@ -4,25 +4,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { AttachmentThumbs } from './attachments';
-// The unit env has neither the MotionProvider nor the image-preview portal the real
-// components need; stub them down to the DOM the assertions actually read.
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children, onClick }: any) => <div onClick={onClick}>{children}</div>,
- Icon: () => null,
- Image: ({ alt, src }: any) => <img alt={alt} src={src} />,
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: ({ children, onClick }: any) => (
- <button type="button" onClick={onClick}>
- {children}
- </button>
- ),
- toast: { error: vi.fn(), success: vi.fn() },
-}));
-
-vi.mock('antd', () => ({ Upload: ({ children }: any) => <div>{children}</div> }));
-
vi.mock('@/store/file', () => ({ useFileStore: () => vi.fn() }));
const attachments = [{ id: 'att-1', name: 'screenshot.png', url: 'https://example.com/a.png' }];
diff --git a/src/features/AgentBreadcrumb/index.test.tsx b/src/features/AgentBreadcrumb/index.test.tsx
index 253ccfe1ed3..f4b02456f64 100644
--- a/src/features/AgentBreadcrumb/index.test.tsx
+++ b/src/features/AgentBreadcrumb/index.test.tsx
@@ -1,5 +1,4 @@
import { render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { MemoryRouter } from 'react-router';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -16,26 +15,6 @@ const mocks = vi.hoisted(() => ({
},
}));
-vi.mock('@lobehub/ui', () => ({
- Icon: () => <span />,
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('antd', async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
-
- return {
- ...actual,
- Breadcrumb: ({ items }: { items: Array<{ title: ReactNode }> }) => (
- <nav>
- {items.map((item, index) => (
- <span key={index}>{item.title}</span>
- ))}
- </nav>
- ),
- };
-});
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string) => (key === 'inbox.title' ? 'Lobe AI' : key),
diff --git a/src/features/AgentBuilder/TopicSelector.test.tsx b/src/features/AgentBuilder/TopicSelector.test.tsx
index c007c9e3c1e..b2a55a93d05 100644
--- a/src/features/AgentBuilder/TopicSelector.test.tsx
+++ b/src/features/AgentBuilder/TopicSelector.test.tsx
@@ -9,12 +9,10 @@ import TopicSelector from './TopicSelector';
const switchTopic = vi.fn();
const useFetchTopics = vi.fn();
-vi.mock('@lobehub/ui', () => ({
- DropdownMenu: ({ children }: any) => <div>{children}</div>,
- Flexbox: ({ children }: any) => <div>{children}</div>,
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
+// Real base-ui ActionIcon only surfaces its title via a hover Tooltip, so the
+// static DOM has no accessible name to query.
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
ActionIcon: ({ disabled, onClick, title }: any) => (
<button disabled={disabled} type="button" onClick={onClick}>
{title}
@@ -22,13 +20,6 @@ vi.mock('@lobehub/ui/base-ui', () => ({
),
}));
-vi.mock('antd-style', () => ({
- createStaticStyles: () => ({
- time: 'time',
- title: 'title',
- }),
-}));
-
vi.mock('dayjs', () => {
const dayjs = () => ({
diff: () => 0,
@@ -38,10 +29,6 @@ vi.mock('dayjs', () => {
return { default: dayjs };
});
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/const/layoutTokens', () => ({
DESKTOP_HEADER_ICON_SMALL_SIZE: 24,
}));
diff --git a/src/features/AgentDocumentPage/index.test.tsx b/src/features/AgentDocumentPage/index.test.tsx
index e76ef424306..3f7e81dbc6b 100644
--- a/src/features/AgentDocumentPage/index.test.tsx
+++ b/src/features/AgentDocumentPage/index.test.tsx
@@ -13,12 +13,6 @@ vi.mock('react-router', () => ({
useParams: () => ({ aid: 'agent-from-url' }),
}));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
- <div {...(props as Record<string, unknown>)}>{children}</div>
- ),
-}));
-
const pageEditorProps = vi.hoisted(() => ({
current: undefined as undefined | Record<string, unknown>,
}));
diff --git a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
index 9d3c2eea4ec..48bf53e0967 100644
--- a/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
+++ b/src/features/AgentDocumentsExplorer/DocumentExplorerTree.test.tsx
@@ -22,29 +22,6 @@ const modalConfirm = vi.hoisted(() => vi.fn());
const openDocumentMock = vi.hoisted(() => vi.fn());
const removeDocumentMock = vi.hoisted(() => vi.fn());
-vi.mock('@lobehub/ui', () => ({
- ActionIcon: ({
- icon,
- onClick,
- title,
- }: {
- icon?: { displayName?: string; name?: string };
- onClick?: () => void;
- title?: string;
- }) => (
- <button aria-label={title} data-icon={icon?.displayName ?? icon?.name} onClick={onClick}>
- {title}
- </button>
- ),
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Icon: () => <span />,
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('@lobehub/ui/icons', () => ({
- SkillsIcon: () => null,
-}));
-
vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
...((await importOriginal()) as Record<string, unknown>),
ActionIcon: ({
@@ -79,7 +56,8 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
),
}));
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
message: { error: messageError, success: messageSuccess, warning: messageWarning },
@@ -98,12 +76,6 @@ vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
useWorkspaceAwareNavigate: () => navigateMock,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('@/features/ExplorerTree', () => {
interface MockExplorerTreeProps {
canDrag?: (node: ExplorerTreeNode<unknown>) => boolean;
diff --git a/src/features/AgentIdentityModal/useAgentIdentityForm.test.ts b/src/features/AgentIdentityModal/useAgentIdentityForm.test.ts
index 1467f1ef324..2a399879706 100644
--- a/src/features/AgentIdentityModal/useAgentIdentityForm.test.ts
+++ b/src/features/AgentIdentityModal/useAgentIdentityForm.test.ts
@@ -16,10 +16,6 @@ vi.mock('@/store/home', () => ({
selector({ refreshAgentList: mocks.refreshAgentList }),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/services/agent', () => ({
agentService: {
updateAgentSlug: (...args: unknown[]) => mocks.updateAgentSlug(...args),
diff --git a/src/features/AgentSidebar/Header/Nav.test.tsx b/src/features/AgentSidebar/Header/Nav.test.tsx
index 7e4d6042c01..bca04dfc390 100644
--- a/src/features/AgentSidebar/Header/Nav.test.tsx
+++ b/src/features/AgentSidebar/Header/Nav.test.tsx
@@ -26,31 +26,6 @@ vi.mock('@/features/ResourcePermission/useResourceAccess', () => ({
useResourceAccess: () => ({ canEditResource: true, isAccessResolved: true }),
}));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
- <div {...props}>{children}</div>
- ),
-}));
-
-vi.mock('@lobehub/ui/icons', () => ({
- BotPromptIcon: () => null,
-}));
-
-vi.mock('lucide-react', () => ({
- DnaIcon: () => null,
- ListTodoIcon: () => null,
- MessageSquarePlusIcon: () => null,
- MessagesSquareIcon: () => null,
- SearchIcon: () => null,
- TargetIcon: () => null,
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('react-router', async () => {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const actual = (await vi.importActual('react-router')) as typeof import('react-router');
diff --git a/src/features/AgentSidebar/Task/TaskItem.test.tsx b/src/features/AgentSidebar/Task/TaskItem.test.tsx
index d70d38788ed..a2e576888cf 100644
--- a/src/features/AgentSidebar/Task/TaskItem.test.tsx
+++ b/src/features/AgentSidebar/Task/TaskItem.test.tsx
@@ -12,10 +12,6 @@ const mocks = vi.hoisted(() => ({
params: {} as { aid?: string },
}));
-vi.mock('@lobehub/ui', () => ({
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
vi.mock('@/features/NavPanel/components/NavItem', () => ({
default: ({
active,
diff --git a/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsx b/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsx
index 85a98f18d1f..a332dbbf6bc 100644
--- a/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/MetaHoverCard.test.tsx
@@ -9,34 +9,11 @@ import MetaHoverCard from './MetaHoverCard';
const fetchTopicLinkedPullRequestMock = vi.hoisted(() => vi.fn());
-vi.mock('@lobehub/ui', () => ({
- Icon: () => <span data-testid="meta-card-icon" />,
-}));
-
vi.mock('@/store/chat', () => ({
useChatStore: (selector: (state: unknown) => unknown) =>
selector({ useFetchTopicLinkedPullRequest: fetchTopicLinkedPullRequestMock }),
}));
-vi.mock('antd-style', () => ({
- createStaticStyles: () => ({
- card: 'card',
- header: 'header',
- headerTime: 'headerTime',
- headerTitle: 'headerTitle',
- prLink: 'prLink',
- row: 'row',
- rowIcon: 'rowIcon',
- rowText: 'rowText',
- }),
- cssVar: {
- colorError: '#f00',
- colorSuccess: '#0f0',
- colorTextTertiary: '#999',
- colorWarning: '#fa0',
- },
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, string>) =>
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
index 5cf300e1124..06584bcd4e4 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
@@ -2,7 +2,7 @@
* @vitest-environment happy-dom
*/
import { render, screen, waitFor } from '@testing-library/react';
-import type { CSSProperties, ReactNode } from 'react';
+import type { ReactNode } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import TopicItem from './index';
@@ -17,43 +17,13 @@ const topicMetaCardMock = vi.hoisted(() => ({
value: undefined as { pullRequest?: { state: string } } | undefined,
}));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
- <div {...props}>{children}</div>
- ),
+// Assertions key on the raw lucide displayName, which the real Icon does not
+// expose in the DOM.
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Icon: ({ icon }: { icon?: { displayName?: string } }) => (
<div data-icon={icon?.displayName} data-testid="topic-item-icon" />
),
- Popover: ({ children }: { children?: ReactNode }) => <>{children}</>,
- Skeleton: {
- Button: (props: Record<string, unknown>) => <div {...props} />,
- },
- Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- ContextMenuTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,
- Tag: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Text: ({ children, style }: { children?: ReactNode; style?: CSSProperties }) => (
- <span style={style}>{children}</span>
- ),
-}));
-
-vi.mock('antd-style', () => ({
- // `ContextMenuTrigger` comes from the base-ui barrel, which pulls in
- // ScrollArea's global style at import time.
- createGlobalStyle: () => () => null,
- createStaticStyles: () => ({
- dotContainer: 'dotContainer',
- neonDot: 'neonDot',
- neonDotWrapper: 'neonDotWrapper',
- }),
- cssVar: {
- colorInfo: '#00f',
- colorTextDescription: '#999',
- },
- keyframes: () => 'keyframes',
- useTheme: () => ({ isDarkMode: false }),
}));
vi.mock('motion/react', () => ({
@@ -68,12 +38,6 @@ vi.mock('motion/react', () => ({
},
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('@/const/version', () => ({ isDesktop: false }));
vi.mock('@/features/NavPanel/components/NavItem', () => ({
default: ({
diff --git a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.test.tsx b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.test.tsx
index 3f74f7240a1..77daffb5925 100644
--- a/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/useDropdownMenu.test.tsx
@@ -12,17 +12,8 @@ const permissionMock = vi.hoisted(() => ({
}));
const versionMock = vi.hoisted(() => ({ isDesktop: false }));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Icon: () => null,
-}));
-
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
message: {
diff --git a/src/features/AgentSidebar/Topic/List/index.test.tsx b/src/features/AgentSidebar/Topic/List/index.test.tsx
index bf2d624b94e..23d243b6522 100644
--- a/src/features/AgentSidebar/Topic/List/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/index.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { fireEvent, render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import TopicList from './index';
@@ -110,12 +109,6 @@ vi.mock('@/store/user/selectors', () => ({
},
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('../AllTopicsDrawer', () => ({
default: ({ open }: { open: boolean }) => (
<div data-open={String(open)} data-testid="all-topics-drawer" />
@@ -138,16 +131,6 @@ vi.mock('./Item', () => ({
default: () => <div data-testid="topic-item" />,
}));
-// Partial mock: keep every real export (e.g. `lobeStaticStylish`, which
-// `createStaticStyles` reads at import time in transitively-loaded modules like
-// ShareModal/useContainerStyles) and override only Flexbox. A full mock returning
-// just Flexbox drops those exports and crashes collection whenever the suite's
-// module graph evaluates one of them.
-vi.mock('@lobehub/ui', async (importOriginal) => ({
- ...(await importOriginal<Record<string, unknown>>()),
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
-}));
-
describe('Agent topic list', () => {
beforeEach(() => {
pushMock.mockReset();
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
index 7456c76067a..8d8370f8e6e 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { fireEvent, render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import GroupItem from './GroupItem';
@@ -23,67 +22,6 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
...(await import('~base-ui-stubs')).baseUiStubs,
}));
-vi.mock('@lobehub/ui', () => ({
- AccordionItem: ({
- action,
- children,
- title,
- }: {
- action?: ReactNode;
- children?: ReactNode;
- title?: ReactNode;
- }) => (
- <section>
- <div>
- {title}
- {action}
- </div>
- {children}
- </section>
- ),
- ActionIcon: ({
- onClick,
- title,
- }: {
- onClick?: (event: { stopPropagation: () => void }) => void;
- title?: string;
- }) => (
- <button
- aria-label={title}
- type="button"
- onClick={() => onClick?.({ stopPropagation: vi.fn() })}
- />
- ),
- Center: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Icon: () => <span />,
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
- Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
-}));
-
-vi.mock('antd-style', async (importOriginal) => ({
- ...(await importOriginal<object>()),
- createStaticStyles: () => ({
- addTopicAction: 'addTopicAction',
- statusBadge: 'statusBadge',
- statusBadgeError: 'statusBadgeError',
- statusBadgeLoading: 'statusBadgeLoading',
- statusBadgeWaiting: 'statusBadgeWaiting',
- unreadDot: 'unreadDot',
- unreadRipple: 'unreadRipple',
- unreadWrapper: 'unreadWrapper',
- }),
- cssVar: {
- colorError: '#f00',
- colorInfo: '#00f',
- colorTextSecondary: '#666',
- colorTextTertiary: '#999',
- colorWarning: '#fa0',
- },
- cx: (...classes: Array<string | undefined>) => classes.filter(Boolean).join(' '),
- keyframes: () => 'keyframes',
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, options?: { directory?: string }) =>
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx
index 4ffa06979ce..14bd5d8a36a 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx
@@ -6,17 +6,8 @@ import { describe, expect, it, vi } from 'vitest';
import { useThreadItemDropdownMenu } from './useDropdownMenu';
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Icon: () => null,
-}));
-
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
modal: {
diff --git a/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx b/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx
index cf105ed885d..5b7d92d14e9 100644
--- a/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx
+++ b/src/features/AgentSidebar/Topic/useDropdownMenu.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { renderHook } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useTopicActionsDropdownMenu } from './useDropdownMenu';
@@ -43,36 +42,25 @@ vi.mock('@/store/user', () => ({
useUserStore: () => userMock.currentUserId,
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
confirmModal: confirmModalMock,
toast: messageMock,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Icon: () => null,
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ App: {
+ useApp: () => ({
+ message: messageMock,
+ modal: {
+ confirm: vi.fn(),
+ error: vi.fn(),
+ },
+ }),
+ },
}));
-vi.mock('antd', () => {
- return {
- App: {
- useApp: () => ({
- message: messageMock,
- modal: {
- confirm: vi.fn(),
- error: vi.fn(),
- },
- }),
- },
- Upload: ({ children }: { children: ReactNode }) => <>{children}</>,
- };
-});
-
vi.mock('@/hooks/usePermission', () => ({
usePermission: (action: 'create_content' | 'edit_own_content') => ({
allowed: permissionMock[action],
diff --git a/src/features/AgentTaskManager/AgentSelectorAction.test.tsx b/src/features/AgentTaskManager/AgentSelectorAction.test.tsx
index ed1490e6686..6c343fdb1e7 100644
--- a/src/features/AgentTaskManager/AgentSelectorAction.test.tsx
+++ b/src/features/AgentTaskManager/AgentSelectorAction.test.tsx
@@ -39,11 +39,10 @@ const mocks = vi.hoisted(() => ({
},
}));
-vi.mock('@lobehub/ui', () => ({
- Center: ({ children }: { children: ReactNode }) => (
- <div data-testid="selector-trigger">{children}</div>
- ),
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+// The real Popover only mounts its content after an open interaction; the
+// assertions read the selector list synchronously.
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Popover: ({
children,
content,
@@ -62,19 +61,6 @@ vi.mock('@lobehub/ui', () => ({
),
}));
-vi.mock('antd-style', () => ({
- createStaticStyles: () => ({
- chevron: 'chevron',
- container: 'container',
- }),
- cx: (...classes: string[]) => classes.filter(Boolean).join(' '),
-}));
-
-vi.mock('lucide-react', () => ({
- ChevronsUpDownIcon: () => <span data-testid="chevron" />,
- Circle: () => <span data-testid="circle" />,
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string) => (key === 'taskManager.agent' ? 'Task Manager' : key),
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx
index bc8958a97d1..2a66bc87c23 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskAcceptance.test.tsx
@@ -39,38 +39,15 @@ const mocks = vi.hoisted(() => ({
updateVerifyConfig: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => ({
+// Real base-ui ActionIcon only surfaces its title via a hover Tooltip; the
+// assertions click the title text directly.
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
<button type="button" onClick={onClick}>
{title}
</button>
),
- Block: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
- <div onClick={onClick}>{children}</div>
- ),
- Drawer: ({ children, open }: { children: ReactNode; open?: boolean }) =>
- open ? <aside>{children}</aside> : null,
- Flexbox: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
- <div onClick={onClick}>{children}</div>
- ),
- Icon: () => <span />,
- Tag: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
- <button type="button" onClick={onClick}>
- {title}
- </button>
- ),
- Button: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
- <button type="button" onClick={onClick}>
- {children}
- </button>
- ),
- Tag: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
confirmModal: (opts: unknown) => mocks.confirmModal(opts),
}));
@@ -78,33 +55,11 @@ vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
useWorkspaceAwareNavigate: () => mocks.navigate,
}));
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: { useApp: () => ({ message: { error: vi.fn() } }) },
}));
-vi.mock('antd-style', () => ({
- cx: (...classNames: unknown[]) => classNames.filter(Boolean).join(' '),
- createStaticStyles: () => ({
- body: 'body',
- drawerBody: 'drawerBody',
- error: 'error',
- group: 'group',
- groupHeader: 'groupHeader',
- list: 'list',
- row: 'row',
- seq: 'seq',
- }),
- cssVar: {
- colorTextDescription: '#999',
- colorTextQuaternary: '#aaa',
- colorTextSecondary: '#666',
- },
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/components/NeuralNetworkLoading', () => ({ default: () => <div>loading</div> }));
vi.mock('@/features/Acceptance', async () => ({
@@ -138,10 +93,6 @@ vi.mock('@/features/Acceptance', async () => ({
},
}));
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/services/verify', () => ({
verifyService: {
deleteAcceptance: (id: string) => mocks.deleteAcceptance(id),
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
index 6ad86a3c614..e39b00c5a4d 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskDetailHeaderActions.test.tsx
@@ -35,23 +35,22 @@ const mocks = vi.hoisted(() => ({
updateTaskVisibility: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => ({
- ActionIcon: ({ title }: { title?: string }) => <button type="button">{title}</button>,
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
DropdownMenu: ({ children, items }: { children?: ReactNode; items: MenuItem[] }) => {
mocks.dropdownItems = items;
return <>{children}</>;
},
- Icon: () => <span />,
copyToClipboard: vi.fn(),
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ title }: { title?: string }) => <button type="button">{title}</button>,
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
confirmModal: (opts: unknown) => mocks.confirmModal(opts),
- toast: { error: vi.fn(), success: vi.fn() },
}));
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
message: { success: mocks.messageSuccess },
@@ -59,12 +58,6 @@ vi.mock('antd', () => ({
},
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => mocks.activeWorkspaceId,
}));
@@ -103,10 +96,6 @@ vi.mock('@/hooks/useAppOrigin', () => ({
useAppOrigin: () => 'https://example.com',
}));
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/store/task', () => ({
useTaskStore: (selector: (state: Record<string, unknown>) => unknown) =>
selector({
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx
index f1a41133e54..a51d410b557 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskParentBar.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import TaskParentBar from './TaskParentBar';
@@ -25,29 +24,6 @@ const createState = (parent: any) => ({
},
});
-vi.mock('@lobehub/ui', () => ({
- Button: ({
- children,
- icon,
- onClick,
- }: {
- children: ReactNode;
- icon?: ReactNode;
- onClick?: () => void;
- }) => (
- <button type="button" onClick={onClick}>
- {icon}
- {children}
- </button>
- ),
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('react-router', () => ({
useNavigate: () => mocks.navigate,
}));
diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx
index 7d0a39cec39..15e0bced52c 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TaskSubtasks.test.tsx
@@ -34,38 +34,12 @@ const mocks = vi.hoisted(() => ({
} as any,
}));
-vi.mock('@lobehub/ui', () => ({
- ActionIcon: ({ onClick }: { onClick?: () => void }) => (
- <button type="button" onClick={onClick}>
- action
- </button>
- ),
- Block: ({
- children,
- clickable,
- onClick,
- }: {
- children: ReactNode;
- clickable?: boolean;
- onClick?: () => void;
- }) =>
- clickable ? (
- <button type="button" onClick={onClick}>
- {children}
- </button>
- ) : (
- <div>{children}</div>
- ),
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Icon: () => <span>icon</span>,
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
vi.mock('@/libs/contextMenu', () => ({
showContextMenu: mocks.showContextMenu,
}));
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
message: { error: vi.fn(), info: vi.fn(), success: vi.fn(), warning: vi.fn() },
@@ -101,33 +75,14 @@ vi.mock('antd', () => ({
),
}));
-vi.mock('antd-style', () => ({
+vi.mock('antd-style', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
cssVar: {
colorTextDescription: '#999',
colorTextSecondary: '#666',
},
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ onClick }: { onClick?: () => void }) => (
- <button type="button" onClick={onClick}>
- action
- </button>
- ),
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- confirmModal: vi.fn(),
- toast: {
- error: vi.fn(),
- info: vi.fn(),
- success: vi.fn(),
- warning: vi.fn(),
- },
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('react-router', () => ({
useNavigate: () => mocks.navigate,
}));
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicCard.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicCard.test.tsx
index 8a19fb59b9f..8b7583f29a1 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicCard.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicCard.test.tsx
@@ -9,28 +9,6 @@ import { describe, expect, it, vi } from 'vitest';
import TopicCard from './TopicCard';
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ onClick }: { onClick?: () => void }) => (
- <button type="button" onClick={onClick}>
- action
- </button>
- ),
- Avatar: () => <span>avatar</span>,
- Tag: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- confirmModal: vi.fn(),
- toast: {
- error: vi.fn(),
- info: vi.fn(),
- success: vi.fn(),
- warning: vi.fn(),
- },
-}));
-
vi.mock('@/store/task', () => ({
useTaskStore: (selector: (state: any) => unknown) =>
selector({
@@ -42,10 +20,6 @@ vi.mock('@/store/task', () => ({
}),
}));
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/hooks/useActivityTime', () => ({
useActivityTime: () => ({ text: '4m ago', title: '4m ago' }),
}));
diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx
index 81deea7b9d9..92b09309b20 100644
--- a/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx
+++ b/src/features/AgentTasks/AgentTaskDetail/TopicChatDrawer/index.test.tsx
@@ -59,7 +59,8 @@ const mocks = vi.hoisted(() => ({
const serializeSize = (size: unknown) =>
size === undefined ? '' : typeof size === 'string' ? size : JSON.stringify(size);
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
copyToClipboard: vi.fn(),
DropdownMenu: ({
children,
@@ -79,19 +80,10 @@ vi.mock('@lobehub/ui', () => ({
)}
</>
),
- Flexbox: ({
- children,
- flex,
- style,
- }: {
- children?: ReactNode;
- flex?: CSSProperties['flex'];
- style?: CSSProperties;
- }) => <div style={{ flex, ...style }}>{children}</div>,
- Freeze: ({ children }: { children?: ReactNode; frozen?: boolean }) => <>{children}</>,
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
ActionIcon: ({
disabled,
icon,
@@ -116,19 +108,6 @@ vi.mock('@lobehub/ui/base-ui', () => ({
{title}
</button>
),
- Tag: ({ children, title }: { children?: ReactNode; title?: string }) => (
- <span title={title}>{children}</span>
- ),
- Text: ({ children, style }: { children?: ReactNode; style?: CSSProperties }) => (
- <span style={style}>{children}</span>
- ),
- confirmModal: vi.fn(),
- toast: {
- error: vi.fn(),
- info: vi.fn(),
- success: vi.fn(),
- warning: vi.fn(),
- },
FloatingPanel: ({
actions,
children,
@@ -185,12 +164,6 @@ vi.mock('next/dynamic', () => ({
},
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('@/features/Conversation/ChatList', () => ({
default: () => <div data-testid="chat-list" />,
}));
diff --git a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
index 5097a94976c..482e41ea6be 100644
--- a/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
+++ b/src/features/AgentTasks/AgentTaskList/CreateTaskInlineEntry.test.tsx
@@ -28,41 +28,8 @@ vi.mock('@lobehub/editor/react', () => ({
}),
}));
-// Stub the base-ui Button (submit) to a native button — it needs a
-// MotionProvider the app sets up globally but the unit env doesn't.
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: ({
- children,
- disabled,
- onClick,
- }: {
- children?: ReactNode;
- disabled?: boolean;
- onClick?: () => void;
- }) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- ),
- ActionIcon: ({
- onClick,
- style,
- title,
- }: {
- onClick?: () => void;
- style?: CSSProperties;
- title?: string;
- }) => (
- <div
- aria-label={title}
- role="button"
- style={{ height: 24, width: 24, ...style }}
- onClick={onClick}
- >
- {title}
- </div>
- ),
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
toast: { error: vi.fn(), success: vi.fn() },
}));
@@ -135,10 +102,6 @@ vi.mock('../shared/useAgentVisibility', () => ({
useAgentVisibility: (agentId?: string) => (agentId === 'agent-private' ? 'private' : undefined),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
describe('CreateTaskInlineEntry', () => {
beforeEach(() => {
permissionMock.allowed = true;
@@ -182,7 +145,9 @@ describe('CreateTaskInlineEntry', () => {
expect(assigneeControl?.style.getPropertyValue('--lobe-flex-height')).toBe('24px');
expect(assigneeControl?.style.getPropertyValue('--lobe-flex-padding-block')).toBe('3px');
- const attachmentAction = container.querySelector<HTMLElement>('[role="button"]');
+ const attachmentAction = container
+ .querySelector('svg.lucide-paperclip')
+ ?.closest<HTMLElement>('button');
expect(attachmentAction).toHaveStyle({ height: '24px', width: '24px' });
expect(attachmentAction?.parentElement?.style.getPropertyValue('--lobe-flex-align')).toBe(
'center',
diff --git a/src/features/AgentTasks/AgentTaskList/TaskListVisibilityFilter.test.tsx b/src/features/AgentTasks/AgentTaskList/TaskListVisibilityFilter.test.tsx
index 51b9cf948f3..043e4fc540f 100644
--- a/src/features/AgentTasks/AgentTaskList/TaskListVisibilityFilter.test.tsx
+++ b/src/features/AgentTasks/AgentTaskList/TaskListVisibilityFilter.test.tsx
@@ -12,8 +12,8 @@ const taskStoreMock = vi.hoisted(() => ({
visibility: 'workspace',
}));
-vi.mock('@lobehub/ui', () => ({
- ActionIcon: () => <span>Visibility</span>,
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
DropdownMenu: ({
children,
items,
@@ -33,11 +33,6 @@ vi.mock('@lobehub/ui', () => ({
Icon: () => <span data-testid="menu-extra-icon" />,
}));
-vi.mock('antd-style', async (importOriginal) => ({
- ...(await importOriginal<object>()),
- cssVar: { colorTextSecondary: '#666' },
-}));
-
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => 'workspace-1',
}));
@@ -50,10 +45,6 @@ vi.mock('@/store/task', () => ({
}),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
describe('TaskListVisibilityFilter', () => {
it('shows a trailing checkmark only for the active visibility option', () => {
render(<TaskListVisibilityFilter />);
diff --git a/src/features/AgentTasks/TaskWorkspaceLayout.test.tsx b/src/features/AgentTasks/TaskWorkspaceLayout.test.tsx
index 456d0dee7d7..657d4498512 100644
--- a/src/features/AgentTasks/TaskWorkspaceLayout.test.tsx
+++ b/src/features/AgentTasks/TaskWorkspaceLayout.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import TaskWorkspaceLayout from './TaskWorkspaceLayout';
@@ -11,12 +10,6 @@ const mocks = vi.hoisted(() => ({
isMobile: false,
}));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
- <div {...props}>{children}</div>
- ),
-}));
-
vi.mock('react-router', async () => {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const actual = (await vi.importActual('react-router')) as typeof import('react-router');
diff --git a/src/features/AgentTasks/features/AgentTaskItem.test.tsx b/src/features/AgentTasks/features/AgentTaskItem.test.tsx
index e017c8f8217..11fbb257c5b 100644
--- a/src/features/AgentTasks/features/AgentTaskItem.test.tsx
+++ b/src/features/AgentTasks/features/AgentTaskItem.test.tsx
@@ -13,28 +13,6 @@ const mocks = vi.hoisted(() => ({
useFetchTaskDetail: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => ({
- Block: ({
- children,
- clickable,
- onClick,
- }: {
- children: ReactNode;
- clickable?: boolean;
- onClick?: () => void;
- }) =>
- clickable ? (
- <button data-testid="task-card" type="button" onClick={onClick}>
- {children}
- </button>
- ) : (
- <span>{children}</span>
- ),
- ContextMenuTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
i18n: { language: 'en-US' },
@@ -132,7 +110,7 @@ describe('AgentTaskItem', () => {
it('opens an assigned task inside its owning agent route', () => {
render(<AgentTaskItem task={createTask('agt_owner')} />);
- fireEvent.click(screen.getByTestId('task-card'));
+ fireEvent.click(screen.getByText('Hourly trend update'));
expect(mocks.navigate).toHaveBeenCalledWith('/agent/agt_owner/task/T-22');
});
@@ -140,7 +118,7 @@ describe('AgentTaskItem', () => {
it('opens an assigned task on the global detail route in global scope', () => {
render(<AgentTaskItem routeScope="global" task={createTask('agt_owner')} />);
- fireEvent.click(screen.getByTestId('task-card'));
+ fireEvent.click(screen.getByText('Hourly trend update'));
expect(mocks.navigate).toHaveBeenCalledWith('/task/T-22');
});
@@ -148,7 +126,7 @@ describe('AgentTaskItem', () => {
it('falls back to the global task detail route when the task has no assignee', () => {
render(<AgentTaskItem task={createTask(null)} />);
- fireEvent.click(screen.getByTestId('task-card'));
+ fireEvent.click(screen.getByText('Hourly trend update'));
expect(mocks.navigate).toHaveBeenCalledWith('/task/T-22');
});
diff --git a/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx b/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx
index fe667eeb994..9741c5498d8 100644
--- a/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx
+++ b/src/features/AgentTasks/features/TaskSubtaskProgressTag.test.tsx
@@ -7,10 +7,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import TaskSubtaskProgressTag from './TaskSubtaskProgressTag';
-vi.mock('@lobehub/ui', () => ({
- Block: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
- <div onClick={onClick}>{children}</div>
- ),
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
DropdownMenu: ({
children,
items,
@@ -32,23 +30,6 @@ vi.mock('@lobehub/ui', () => ({
))}
</div>
),
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('antd', () => ({
- Progress: () => <span>progress</span>,
-}));
-
-vi.mock('antd-style', () => ({
- cssVar: { colorSuccess: 'green' },
}));
vi.mock('./TaskStatusIcon', () => ({
diff --git a/src/features/AgentTasks/features/TaskVisibilityChipLabel.test.tsx b/src/features/AgentTasks/features/TaskVisibilityChipLabel.test.tsx
index 210d094d90b..ebcea8f8536 100644
--- a/src/features/AgentTasks/features/TaskVisibilityChipLabel.test.tsx
+++ b/src/features/AgentTasks/features/TaskVisibilityChipLabel.test.tsx
@@ -2,25 +2,10 @@
* @vitest-environment happy-dom
*/
import { render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { describe, expect, it, vi } from 'vitest';
import TaskVisibilityChipLabel from './TaskVisibilityChipLabel';
-vi.mock('@lobehub/ui', () => ({
- Block: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Icon: () => <span />,
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('antd-style', async (importOriginal) => ({
- ...(await importOriginal<object>()),
- cssVar: {
- colorTextDescription: '#999',
- colorTextSecondary: '#666',
- },
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, options?: { defaultValue?: string }) => {
diff --git a/src/features/AgentTasks/features/TaskVisibilityTag.test.tsx b/src/features/AgentTasks/features/TaskVisibilityTag.test.tsx
index abb86f988fe..ba1bc05bea5 100644
--- a/src/features/AgentTasks/features/TaskVisibilityTag.test.tsx
+++ b/src/features/AgentTasks/features/TaskVisibilityTag.test.tsx
@@ -7,7 +7,8 @@ import { describe, expect, it, vi } from 'vitest';
import TaskVisibilityTag from './TaskVisibilityTag';
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
DropdownMenu: ({
children,
items,
@@ -25,15 +26,6 @@ vi.mock('@lobehub/ui', () => ({
</>
),
Icon: () => <span data-testid="menu-extra-icon" />,
- Tooltip: ({ children }: { children: ReactNode }) => children,
-}));
-
-vi.mock('antd-style', () => ({
- createStaticStyles: () => ({ trigger: 'trigger', triggerDisabled: 'trigger-disabled' }),
- cssVar: {
- colorTextDescription: '#999',
- colorTextSecondary: '#666',
- },
}));
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
diff --git a/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx b/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx
index e17e1300607..4c4f6f78604 100644
--- a/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx
+++ b/src/features/AgentTasks/features/useTaskItemContextMenu.test.tsx
@@ -1,6 +1,5 @@
import { act, renderHook } from '@testing-library/react';
import type { ReactNode } from 'react';
-import React from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { canGoNative } from '@/libs/contextMenu/canGoNative';
@@ -23,18 +22,17 @@ const mocks = vi.hoisted(() => ({
updateTaskStatus: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
copyToClipboard: mocks.copyToClipboard,
- Flexbox: ({ children }: { children?: ReactNode }) => React.createElement('div', {}, children),
- Icon: ({ icon: Icon }: { icon?: React.ComponentType }) =>
- Icon ? React.createElement(Icon) : React.createElement('span'),
}));
vi.mock('@/libs/contextMenu', () => ({
closeContextMenu: mocks.closeContextMenu,
}));
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
message: { success: mocks.messageSuccess },
@@ -51,10 +49,6 @@ vi.mock('@/hooks/useAppOrigin', () => ({
useAppOrigin: () => 'https://example.com',
}));
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/store/agent', () => ({
useAgentStore: (selector: (state: { inboxAgentId: string }) => unknown) =>
selector({ inboxAgentId: 'inbox-agent' }),
diff --git a/src/features/AgentTasks/shared/Breadcrumb.test.tsx b/src/features/AgentTasks/shared/Breadcrumb.test.tsx
index 90a945253a0..2acb74d2fdc 100644
--- a/src/features/AgentTasks/shared/Breadcrumb.test.tsx
+++ b/src/features/AgentTasks/shared/Breadcrumb.test.tsx
@@ -15,27 +15,6 @@ const createState = (taskDetailMap: Record<string, any>) => ({
taskDetailMap,
});
-vi.mock('@lobehub/ui', () => ({
- Icon: () => <span>icon</span>,
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('antd', () => ({
- Breadcrumb: ({ items }: { items: Array<{ key?: string; title: ReactNode }> }) => (
- <nav>
- {items.map((item, index) => (
- <span data-testid="crumb" key={item.key ?? index}>
- {item.title}
- </span>
- ))}
- </nav>
- ),
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('react-router', () => ({
Link: ({ children, to }: { children: ReactNode; to: string }) => <a href={to}>{children}</a>,
useParams: () => ({}),
diff --git a/src/features/Auth/SignIn/useSignIn.test.ts b/src/features/Auth/SignIn/useSignIn.test.ts
index c6705ea81f9..3c99e5e7f7d 100644
--- a/src/features/Auth/SignIn/useSignIn.test.ts
+++ b/src/features/Auth/SignIn/useSignIn.test.ts
@@ -33,7 +33,8 @@ vi.mock('react-router', () => ({
useSearchParams: () => [{ get: mockSearchParamsGet }],
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
toast: { error: mockMessageError, success: mockMessageSuccess },
}));
diff --git a/src/features/Auth/SignUp/useSignUp.test.ts b/src/features/Auth/SignUp/useSignUp.test.ts
index cf5b68beb23..6922e214571 100644
--- a/src/features/Auth/SignUp/useSignUp.test.ts
+++ b/src/features/Auth/SignUp/useSignUp.test.ts
@@ -15,7 +15,8 @@ vi.mock('react-router', () => ({
useSearchParams: () => [{ get: mockSearchParamsGet }],
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
toast: { error: mockMessageError, success: vi.fn() },
}));
diff --git a/src/features/ChatInput/ActionBar/index.test.ts b/src/features/ChatInput/ActionBar/index.test.ts
index 5889e4db7cd..1c1090f72aa 100644
--- a/src/features/ChatInput/ActionBar/index.test.ts
+++ b/src/features/ChatInput/ActionBar/index.test.ts
@@ -12,25 +12,11 @@ const tokenMocks = vi.hoisted(() => ({
useTokenBreakdown: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => {
- const Primitive = ({ children }: { children?: ReactNode }) => createElement('div', {}, children);
-
- return { Center: Primitive, Flexbox: Primitive, Tooltip: Primitive };
-});
-
vi.mock('@lobehub/ui/chat', () => ({
TokenTag: ({ value }: { value: number }) =>
createElement('div', { 'data-testid': 'token-tag' }, value),
}));
-vi.mock('antd-style', () => ({
- cssVar: new Proxy({}, { get: (_, key) => String(key) }),
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/store/user', () => ({
useUserStore: (selector: (state: object) => unknown) => selector({}),
}));
diff --git a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx
index 27da52ab322..3134f4322ca 100644
--- a/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx
+++ b/src/features/ChatInput/ChatInputNotice/useChatInputNotice.test.tsx
@@ -72,7 +72,10 @@ vi.mock('@lobechat/const', () => ({
},
}));
-vi.mock('@lobehub/ui/base-ui', () => ({ toast: { error: toastError } }));
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ toast: { error: toastError },
+}));
vi.mock('@/features/ChatInput/hooks/useAgentId', () => ({
useAgentId: () => 'agent-id',
diff --git a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
index 841cc5cb4c6..009d6e33a48 100644
--- a/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/GitStatus.test.tsx
@@ -84,26 +84,10 @@ vi.mock('@/components/AntdStaticMethods', () => ({
message: { error: vi.fn(), info: vi.fn(), success: vi.fn() },
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- toast: { error: vi.fn(), info: vi.fn(), success: vi.fn() },
-}));
-
vi.mock('@/components/RingLoading', () => ({
default: () => <span data-testid="ring-loading" />,
}));
-vi.mock('@lobehub/ui', () => ({
- Icon: () => <span data-testid="icon" />,
- Tooltip: ({ children, title }: { children: ReactNode; title?: ReactNode }) => (
- <div data-title={typeof title === 'string' ? title : undefined}>{children}</div>
- ),
-}));
-
-vi.mock('antd-style', () => ({
- createStaticStyles: () => ({}),
- cssVar: new Proxy({}, { get: () => 'var(--mock)' }),
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) =>
diff --git a/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
index 51143904c4b..f4fafa65dae 100644
--- a/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/WorktreeSwitcher.test.tsx
@@ -31,17 +31,16 @@ vi.mock('@/services/git', () => ({
},
}));
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Icon: ({ icon }: any) => <span data-icon={icon?.displayName ?? icon?.name} data-testid="icon" />,
- Input: ({ value, onChange, placeholder }: any) => (
- <input placeholder={placeholder} value={value} onChange={onChange} />
- ),
Tooltip: ({ children }: { children: ReactNode }) => (
<span data-testid="worktree-tooltip">{children}</span>
),
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
confirmModal: confirmModalMock,
DropdownMenuItem: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
<button onClick={onClick}>{children}</button>
@@ -63,12 +62,6 @@ vi.mock('@lobehub/ui/base-ui', () => ({
},
}));
-vi.mock('antd-style', () => ({
- createStaticStyles: () => ({}),
- cssVar: new Proxy({}, { get: () => 'var(--mock)' }),
- cx: (...classes: string[]) => classes.filter(Boolean).join(' '),
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) =>
diff --git a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
index 74deded2737..942b949b782 100644
--- a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
+++ b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx
@@ -19,8 +19,6 @@ const testState = vi.hoisted(() => ({
},
}));
-vi.mock('@lobehub/ui/base-ui', () => ({ confirmModal: vi.fn() }));
-
vi.mock('@/hooks/useEffectiveAgencyConfig', () => ({
useEffectiveAgencyConfig: () => testState.effective,
}));
diff --git a/src/features/ChatTerminal/TerminalView.test.tsx b/src/features/ChatTerminal/TerminalView.test.tsx
index f895b087f26..70cea5008ec 100644
--- a/src/features/ChatTerminal/TerminalView.test.tsx
+++ b/src/features/ChatTerminal/TerminalView.test.tsx
@@ -14,7 +14,8 @@ const { manager, preference } = vi.hoisted(() => ({
preference: { terminalFontFamily: '"JetBrains Mono"' },
}));
-vi.mock('antd-style', () => ({
+vi.mock('antd-style', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
useTheme: () => ({ fontFamilyCode: 'Application Mono' }),
}));
diff --git a/src/features/ChatTerminal/index.test.tsx b/src/features/ChatTerminal/index.test.tsx
index 6e264b4b938..9709ff391b1 100644
--- a/src/features/ChatTerminal/index.test.tsx
+++ b/src/features/ChatTerminal/index.test.tsx
@@ -12,7 +12,8 @@ vi.mock('@lobechat/const', async (importOriginal) => ({
isDesktop: true,
}));
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
DraggablePanel: ({ children, expand }: { children?: ReactNode; expand?: boolean }) => (
<div data-expand={String(expand)} data-testid="terminal-panel">
{children}
diff --git a/src/features/Connectors/ConnectorDetail/index.test.tsx b/src/features/Connectors/ConnectorDetail/index.test.tsx
index da4e156d479..d0e53aec194 100644
--- a/src/features/Connectors/ConnectorDetail/index.test.tsx
+++ b/src/features/Connectors/ConnectorDetail/index.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ConnectorSourceType } from '@/database/schemas';
@@ -57,33 +56,6 @@ vi.mock('@/hooks/useResourceManageable', () => ({
useResourceManageable: () => true,
}));
-vi.mock('@lobehub/ui', () => ({
- Tooltip: ({ children }: { children: ReactNode }) => children,
-}));
-
-vi.mock('antd', () => ({
- App: { useApp: () => ({ message: { error: vi.fn() } }) },
-}));
-
-// Stub the base-ui Button to a native button — it needs a MotionProvider the
-// app sets up globally but the unit env doesn't.
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: ({
- children,
- disabled,
- onClick,
- }: {
- children?: ReactNode;
- disabled?: boolean;
- onClick?: () => void;
- }) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- ),
- confirmModal: vi.fn(),
-}));
-
vi.mock('@/store/tool', () => ({
useToolStore<T>(selector: (state: typeof mocks.toolState) => T): T {
return selector(mocks.toolState);
diff --git a/src/features/Conversation/ChatInput/VerifyTray/GoalModal.test.tsx b/src/features/Conversation/ChatInput/VerifyTray/GoalModal.test.tsx
index 2ae72ed9d2f..7d78dbbdff6 100644
--- a/src/features/Conversation/ChatInput/VerifyTray/GoalModal.test.tsx
+++ b/src/features/Conversation/ChatInput/VerifyTray/GoalModal.test.tsx
@@ -5,21 +5,9 @@ import { GoalContent } from './GoalModal';
const mocks = vi.hoisted(() => ({ close: vi.fn() }));
-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('i18next', () => ({ t: (key: string) => key }));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: any) => <div>{children}</div>,
- Text: ({ children }: any) => <span>{children}</span>,
- TextArea: (props: any) => <textarea {...props} />,
-}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: ({ children, onClick, disabled }: any) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- ),
- Text: ({ children }: any) => <span>{children}</span>,
- createModal: vi.fn(),
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
useModalContext: () => ({ close: mocks.close }),
}));
diff --git a/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx b/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx
index e46665405be..0416edd07b4 100644
--- a/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx
+++ b/src/features/Conversation/ChatItem/components/ErrorContent.test.tsx
@@ -14,11 +14,8 @@ let isRegenerating = false;
// Drive the Alert's `afterClose` directly via a click, so we exercise
// ErrorContent's dismiss branching without the real close animation.
-vi.mock('@lobehub/ui', () => ({
- Skeleton: { Button: () => <div>loading</div> },
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Alert: ({ action, afterClose }: { action?: ReactNode; afterClose?: () => void }) => (
<div>
<button type="button" onClick={() => afterClose?.()}>
@@ -27,23 +24,6 @@ vi.mock('@lobehub/ui/base-ui', () => ({
{action}
</div>
),
- Button: ({
- children,
- disabled,
- loading,
- }: {
- children?: ReactNode;
- disabled?: boolean;
- loading?: boolean;
- }) => (
- <button aria-busy={loading || undefined} disabled={disabled} type="button">
- {children}
- </button>
- ),
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock('@/features/Conversation/store', () => ({
diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
index 8181e4ab8ee..17bbf18709a 100644
--- a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
@@ -15,8 +15,6 @@ import {
useConversationScroll,
} from './useConversationScroll';
-vi.mock('zustand/traditional');
-
vi.mock('../../store', async (importOriginal) => {
const actual = await importOriginal<typeof ConversationStoreModule>();
return {
diff --git a/src/features/Conversation/ConversationProvider.test.tsx b/src/features/Conversation/ConversationProvider.test.tsx
index e518c84bd21..3cb36f838ba 100644
--- a/src/features/Conversation/ConversationProvider.test.tsx
+++ b/src/features/Conversation/ConversationProvider.test.tsx
@@ -23,27 +23,6 @@ const chatListMocks = vi.hoisted(() => ({
useFetchAgentConfig: vi.fn(),
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: ({
- children,
- disabled,
- onClick,
- }: {
- children?: ReactNode;
- disabled?: boolean;
- onClick?: () => void;
- }) => (
- <button disabled={disabled} onClick={onClick}>
- {children}
- </button>
- ),
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/features/Conversation/ChatList/components/AgentSignalReceiptList', () => ({
default: () => null,
}));
diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsx
index 2199b964bd3..c92437d2de1 100644
--- a/src/features/Conversation/Error/index.test.tsx
+++ b/src/features/Conversation/Error/index.test.tsx
@@ -1,10 +1,8 @@
-import type * as businessConstModule from '@lobechat/business-const';
import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';
import type * as modelRuntimeModule from '@lobechat/model-runtime';
import { AgentRuntimeErrorType } from '@lobechat/model-runtime';
import type * as lobechatTypesModule from '@lobechat/types';
import { ChatErrorType } from '@lobechat/types';
-import type * as lobehubUiModule from '@lobehub/ui';
import { fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -32,14 +30,6 @@ const businessErrorContentMock = vi.hoisted(() =>
})),
);
-vi.mock('@lobechat/business-const', async (importOriginal) => {
- const actual = (await importOriginal()) as typeof businessConstModule;
-
- return {
- ...actual,
- };
-});
-
vi.mock('@lobechat/model-runtime', async (importOriginal) => {
const actual = (await importOriginal()) as typeof modelRuntimeModule;
@@ -64,20 +54,6 @@ vi.mock('@lobechat/types', async (importOriginal) => {
};
});
-vi.mock('@lobehub/ui', async (importOriginal) => {
- const actual = (await importOriginal()) as typeof lobehubUiModule;
-
- return {
- ...actual,
- Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Highlighter: ({ children }: { children?: ReactNode }) => <pre>{children}</pre>,
- Skeleton: {
- ...actual.Skeleton,
- Button: () => <div>loading</div>,
- },
- };
-});
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, options?: Record<string, unknown>) =>
diff --git a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx
index dd26d485fac..a2f22bc5e5b 100644
--- a/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx
+++ b/src/features/Conversation/Markdown/plugins/Link/Render/index.test.tsx
@@ -35,19 +35,6 @@ const mockOpenDocument = vi.fn();
const mockOpenTaskDetail = vi.fn();
const mockOpenVerifyReport = vi.fn();
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: (props: { onClick?: (e: unknown) => void; title?: string }) => (
- <button
- aria-label={props.title}
- data-side-browser={(props as Record<string, unknown>)['data-side-browser']}
- type="button"
- onClick={props.onClick}
- />
- ),
- Avatar: ({ alt }: { alt?: string }) => <span>{alt}</span>,
- Text: ({ children }: { children?: unknown }) => <span>{children as never}</span>,
-}));
-
vi.mock('@/business/client/hooks/useWorkspaces', () => ({
useWorkspaces: () => [{ id: 'ws-1', slug: 'lobe-team' }],
}));
diff --git a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
index 3d7cf8f5740..45e2712f472 100644
--- a/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
+++ b/src/features/Conversation/Markdown/plugins/LocalFileLink/Render.test.tsx
@@ -2,8 +2,9 @@
* @vitest-environment happy-dom
*/
import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';
+import type { TooltipProps } from '@lobehub/ui';
import { fireEvent, render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
+import type { ComponentType } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { useChatStore } from '@/store/chat';
@@ -40,29 +41,19 @@ vi.mock('@/components/FileIcon', () => ({
),
}));
-vi.mock('@lobehub/ui', async (importOriginal) => ({
- ...((await importOriginal()) as Record<string, unknown>),
- Tooltip: ({
- children,
- mouseEnterDelay,
- placement,
- title,
- }: {
- children: ReactNode;
- mouseEnterDelay?: number;
- placement?: string;
- title?: ReactNode;
- }) => (
- <span
- data-mouse-enter-delay={String(mouseEnterDelay)}
- data-placement={placement}
- data-testid="local-file-tooltip"
- data-title={typeof title === 'string' ? title : undefined}
- >
- {children}
- </span>
- ),
-}));
+const tooltipPropsSpy = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobehub/ui', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ const ActualTooltip = actual.Tooltip as ComponentType<TooltipProps>;
+ return {
+ ...actual,
+ Tooltip: (props: TooltipProps) => {
+ tooltipPropsSpy(props);
+ return <ActualTooltip {...props} />;
+ },
+ };
+});
describe('LocalFileLink Render', () => {
afterEach(() => {
@@ -97,15 +88,13 @@ describe('LocalFileLink Render', () => {
const link = screen.getByRole('link', { name: 'Group.tsx' });
- expect(screen.getByTestId('local-file-tooltip')).toHaveAttribute(
- 'data-title',
- '/Users/me/project/src/Group.tsx (line 265)',
- );
- expect(screen.getByTestId('local-file-tooltip')).toHaveAttribute(
- 'data-mouse-enter-delay',
- '0.1',
+ expect(tooltipPropsSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ mouseEnterDelay: 0.1,
+ placement: 'topLeft',
+ title: '/Users/me/project/src/Group.tsx (line 265)',
+ }),
);
- expect(screen.getByTestId('local-file-tooltip')).toHaveAttribute('data-placement', 'topLeft');
fireEvent.click(link);
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Arguments/index.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Arguments/index.test.tsx
index 8211dae264f..58e0975b35a 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Arguments/index.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Arguments/index.test.tsx
@@ -2,48 +2,28 @@
* @vitest-environment happy-dom
*/
import { fireEvent, render, screen } from '@testing-library/react';
-import type { ComponentType, ReactNode } from 'react';
+import type { ReactNode } from 'react';
import { describe, expect, it, vi } from 'vitest';
import Arguments from './index';
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Highlighter: ({ children, wrap }: { children?: ReactNode; wrap?: boolean }) => (
- <pre data-testid="highlighter" data-wrap={String(Boolean(wrap))}>
- {children}
- </pre>
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ActionIcon: ({
+ active,
+ onClick,
+ title,
+ }: {
+ active?: boolean;
+ onClick?: () => void;
+ title?: string;
+ }) => (
+ <button aria-pressed={active} type="button" onClick={onClick}>
+ {title}
+ </button>
),
}));
-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
- return {
- ...actual,
- ActionIcon: ({
- active,
- icon: IconComponent,
- onClick,
- title,
- }: {
- active?: boolean;
- icon?: ComponentType;
- onClick?: () => void;
- title?: string;
- }) => (
- <button aria-pressed={active} type="button" onClick={onClick}>
- {title}
- {IconComponent ? <IconComponent /> : null}
- </button>
- ),
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
- };
-});
-
-vi.mock('antd', () => ({
- Divider: () => <hr />,
-}));
-
vi.mock('@/components/Descriptions', () => ({
default: ({
items,
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx
index 285b3096bef..28853be7859 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { describe, expect, it, vi } from 'vitest';
import FallbackIntervention from './Fallback';
@@ -13,19 +12,6 @@ const metaMap: Record<string, { avatar?: string; title?: string }> = {
'search': { title: 'Web Search' },
};
-vi.mock('@lobehub/ui', () => ({
- ActionIcon: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
- <button {...props}>{children}</button>
- ),
- Avatar: ({ avatar, title }: { avatar?: string; title?: string }) => (
- <img alt={title} src={avatar} />
- ),
- Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
- <div {...props}>{children}</div>
- ),
- Icon: () => <span>icon</span>,
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, options?: { count?: number; defaultValue?: string }) =>
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/webOnboarding.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/webOnboarding.test.tsx
index c578690dd81..cf3edf6b3b4 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/webOnboarding.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/webOnboarding.test.tsx
@@ -1,23 +1,18 @@
/**
* @vitest-environment happy-dom
*/
+import { WebOnboardingApiName } from '@lobechat/builtin-tool-web-onboarding';
+import { WebOnboardingInterventions } from '@lobechat/builtin-tool-web-onboarding/client';
import { fireEvent, render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { describe, expect, it, vi } from 'vitest';
-vi.mock('@lobehub/ui', () => ({
- Avatar: ({ avatar }: { avatar: string }) => <div>{avatar}</div>,
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
EmojiPicker: ({ onChange, value }: { onChange?: (next: string) => void; value?: string }) => (
<button data-testid="emoji-picker" type="button" onClick={() => onChange?.('🪶')}>
{value || ''}
</button>
),
- Flexbox: ({ children }: { children?: ReactNode; [key: string]: unknown }) => (
- <div>{children}</div>
- ),
- Text: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
- <span {...props}>{children}</span>
- ),
}));
vi.mock('react-i18next', () => ({
@@ -38,13 +33,9 @@ vi.mock('react-i18next', () => ({
}));
describe('web onboarding intervention registry', () => {
- let Component: ReturnType<typeof Object> | undefined;
+ const Component = WebOnboardingInterventions[WebOnboardingApiName.saveUserQuestion];
- beforeEach(async () => {
- const { WebOnboardingInterventions } =
- await import('@lobechat/builtin-tool-web-onboarding/client');
- const { WebOnboardingApiName } = await import('@lobechat/builtin-tool-web-onboarding');
- Component = WebOnboardingInterventions[WebOnboardingApiName.saveUserQuestion];
+ it('registers the saveUserQuestion intervention', () => {
expect(Component).toBeDefined();
});
@@ -90,8 +81,8 @@ describe('web onboarding intervention registry', () => {
if (!Component) throw new TypeError('Expected web onboarding intervention to be registered');
const onArgsChange = vi.fn();
- let beforeApproveCallback: (() => Promise<void>) | undefined;
- const registerBeforeApprove = (_id: string, callback: () => Promise<void>) => {
+ let beforeApproveCallback: (() => void | Promise<void>) | undefined;
+ const registerBeforeApprove = (_id: string, callback: () => void | Promise<void>) => {
beforeApproveCallback = callback;
return () => {
beforeApproveCallback = undefined;
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ExecutionTime.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ExecutionTime.test.tsx
index 35ff2e891a1..62a630404aa 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ExecutionTime.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Inspector/ExecutionTime.test.tsx
@@ -2,15 +2,10 @@
* @vitest-environment happy-dom
*/
import { act, cleanup, render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import ExecutionTime from './ExecutionTime';
-vi.mock('@lobehub/ui', () => ({
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
-}));
-
describe('ExecutionTime', () => {
afterEach(() => {
cleanup();
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx
index cff30ca7012..3a91108b8ae 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx
@@ -15,15 +15,6 @@ const retryFailedAssistantStepMock = vi.fn();
const navigateMock = vi.fn();
let isInReasoningMock = false;
-vi.mock('@lobehub/ui', () => ({
- Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Highlighter: ({ children }: { children?: ReactNode }) => <pre>{children}</pre>,
- Skeleton: {
- Button: () => <div>loading</div>,
- },
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
i18n: {
@@ -69,10 +60,6 @@ vi.mock('@/features/Electron/HeterogeneousAgent/StatusGuide', () => ({
),
}));
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/hooks/useProviderName', () => ({
useProviderName: () => 'Mock Provider',
}));
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.test.tsx
index cbcae17b5c3..58bb0d4d435 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlocksScroll.test.tsx
@@ -2,26 +2,11 @@
* @vitest-environment happy-dom
*/
import { render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { describe, expect, it, vi } from 'vitest';
import ContentBlocksScroll from './ContentBlocksScroll';
import type { RenderableAssistantContentBlock } from './types';
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children, gap }: { children?: ReactNode; gap?: number }) => (
- <div data-gap={gap}>{children}</div>
- ),
- ScrollArea: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
-}));
-
-vi.mock('antd-style', () => ({
- createStaticStyles: () => ({
- scrollTask: 'scroll-task',
- scrollWorkflow: 'scroll-workflow',
- }),
-}));
-
vi.mock('./ContentBlock', () => ({
default: ({ disableMarkdownStreaming, id }: RenderableAssistantContentBlock) => (
<div
@@ -66,7 +51,7 @@ describe('ContentBlocksScroll', () => {
});
it('uses a consistent gap between workflow blocks', () => {
- const { container } = render(
+ render(
<ContentBlocksScroll
assistantId="assistant-1"
scroll={false}
@@ -78,6 +63,7 @@ describe('ContentBlocksScroll', () => {
/>,
);
- expect(container.querySelector('[data-gap="8"]')).toBeInTheDocument();
+ const [firstBlock] = screen.getAllByTestId('content-block');
+ expect(firstBlock.parentElement!.style.getPropertyValue('--lobe-flex-gap')).toBe('8px');
});
});
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx
index d3274e9ee5c..fe56578f533 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/Group.test.tsx
@@ -15,16 +15,6 @@ let mockIsGenerating = false;
let mockDbMessages: { createdAt?: Date | number | string | null; id: string }[] = [];
let mockOperations: { metadata: Record<string, unknown>; status: string }[] = [];
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
-}));
-
-vi.mock('antd-style', () => ({
- createStaticStyles: () => ({
- container: 'group-container',
- }),
-}));
-
vi.mock('@/store/chat', () => ({
useChatStore: (selector: (state: unknown) => unknown) => selector({}),
}));
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.test.tsx
index 3e4b741489c..75fd4502a17 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/MessageContent.test.tsx
@@ -11,13 +11,6 @@ let mockStoreContent = 'original full content';
let mockStoreHasTools = true;
let mockStoreMessage: { createdAt?: number } | undefined = { createdAt: 1000 };
-vi.mock('antd-style', () => ({
- createStaticStyles: () => ({
- pWithTool: 'tool-line',
- }),
- cx: (...values: unknown[]) => values.filter(Boolean).join(' '),
-}));
-
vi.mock('@/features/Conversation/Markdown', () => ({
default: ({ children, className }: { children?: ReactNode; className?: string }) => (
<div className={className} data-testid="markdown">
diff --git a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx
index 54aec2b0dec..1c04f687c41 100644
--- a/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/components/WorkflowCollapse.test.tsx
@@ -11,7 +11,8 @@ import WorkflowCollapse from './WorkflowCollapse';
let mockIsGenerating = true;
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Accordion: ({
children,
expandedKeys,
@@ -64,8 +65,6 @@ vi.mock('@lobehub/ui', () => ({
{IconComponent ? <IconComponent /> : null}
</button>
),
- Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
Icon: ({ icon: IconComponent }: { icon?: ComponentType }) =>
IconComponent ? (
<div
@@ -77,25 +76,11 @@ vi.mock('@lobehub/ui', () => ({
) : (
<div />
),
- ShikiLobeTheme: {},
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({
- icon: IconComponent,
- onClick,
- title,
- }: {
- icon?: ComponentType;
- onClick?: (e: unknown) => void;
- title?: string;
- }) => (
- <button aria-label={title} type="button" onClick={onClick}>
- {IconComponent ? <IconComponent /> : null}
- </button>
- ),
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
}));
vi.mock('motion/react', () => ({
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/comments.test.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/comments.test.ts
index 43f04857033..d603f2af69a 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/actions/comments.test.ts
+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/comments.test.ts
@@ -26,10 +26,6 @@ vi.mock('@/store/chat', () => ({
selector({ activeTopicId: mocks.topicId, openTopicComments: mocks.openTopicComments }),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
const build = () =>
renderHook(() =>
commentsAction.useBuild({
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/copyOperationId.test.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/copyOperationId.test.ts
index ae383d6a7aa..0ad0653157e 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/actions/copyOperationId.test.ts
+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/copyOperationId.test.ts
@@ -27,11 +27,13 @@ vi.mock('@lobehub/ui', () => ({
copyToClipboard: mocks.copyToClipboard,
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
toast: { success: mocks.messageSuccess },
}));
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: { useApp: () => ({ message: { success: mocks.messageSuccess } }) },
}));
@@ -68,10 +70,6 @@ vi.mock('@/store/user/selectors', () => ({
},
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
const build = (
data: Partial<UIChatMessage> = {},
role: MessageActionContext['role'] = 'assistant',
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/del.test.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/del.test.ts
index d5f2df262c0..da71c912c6a 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/actions/del.test.ts
+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/del.test.ts
@@ -16,10 +16,6 @@ vi.mock('../../../../store', () => ({
selector({ deleteAssistantMessage, deleteMessage }),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
// A group's id IS its head child's id — the assistantGroup bubble is a virtual
// message built from the run's first assistant row. Fixtures mirror that.
const build = (
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/regenerate.test.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/regenerate.test.ts
index bf9fbf0f5ad..d55c701a174 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/actions/regenerate.test.ts
+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/regenerate.test.ts
@@ -26,10 +26,6 @@ vi.mock('../../../../store', () => ({
}),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
const build = (
data: Partial<UIChatMessage>,
role: MessageActionContext['role'] = 'assistant',
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.test.ts b/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.test.ts
index d1a39c5df36..91d2ee99c85 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.test.ts
+++ b/src/features/Conversation/Messages/components/MessageActionBar/actions/restoreToInput.test.ts
@@ -29,18 +29,16 @@ vi.mock('@/store/file', () => ({
const { messageSuccess } = vi.hoisted(() => ({ messageSuccess: vi.fn() }));
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
toast: { success: messageSuccess },
}));
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: { useApp: () => ({ message: { success: messageSuccess } }) },
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
const build = (data: Partial<UIChatMessage>, role: MessageActionContext['role'] = 'user') =>
renderHook(() => restoreToInputAction.useBuild({ data: data as UIChatMessage, id: 'm1', role }))
.result.current;
diff --git a/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx b/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx
index 2b171442af2..6a312abcf15 100644
--- a/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx
+++ b/src/features/Conversation/Messages/components/MessageActionBar/index.test.tsx
@@ -14,7 +14,8 @@ const actionMocks = vi.hoisted(() => ({
commentsAvailable: true,
}));
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
ActionIconGroup: ({
items,
menu,
diff --git a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
index e74cb258857..6c69fe2c3da 100644
--- a/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/Files/__tests__/index.test.tsx
@@ -1,5 +1,5 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import type { ReactNode, Ref } from 'react';
+import type { Ref } from 'react';
import { useImperativeHandle } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -185,32 +185,11 @@ vi.mock('@/store/chat', () => ({
const messageSpy = vi.hoisted(() => ({ warning: vi.fn() }));
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
message: messageSpy,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
- ...((await importOriginal()) as Record<string, unknown>),
- ActionIcon: ({ onClick }: { onClick?: () => void }) => (
- <button type={'button'} onClick={onClick} />
- ),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Center: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- copyToClipboard: vi.fn(),
- Empty: ({ description }: { description?: ReactNode }) => <div>{description}</div>,
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Icon: () => <span />,
- stopPropagation: vi.fn(),
-}));
-
vi.mock('antd-style', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>;
diff --git a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
index 68d88a3ee34..a7a9b6e5b86 100644
--- a/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.test.tsx
@@ -4,7 +4,6 @@ import {
AGENT_DOCUMENT_SKILL_CATEGORY,
AGENT_SIGNAL_SOURCE_TYPE,
} from '@lobechat/const';
-import type { ErrorBoundary as LobeErrorBoundary } from '@lobehub/ui';
import { fireEvent, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import type * as ReactRouterDom from 'react-router';
@@ -23,66 +22,13 @@ const removeDocumentMock = vi.hoisted(() => vi.fn());
const useParamsMock = vi.hoisted(() => vi.fn());
const documentExplorerShouldThrow = vi.hoisted(() => ({ current: false }));
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ onClick, title }: { onClick?: (e: React.MouseEvent) => void; title?: string }) => (
- <button aria-label={title} onClick={onClick}>
- {title}
- </button>
- ),
- Alert: ({ message, title }: { message?: ReactNode; title?: ReactNode }) => (
- <div role="alert">
- <div>{title}</div>
- <div>{message}</div>
- </div>
- ),
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
confirmModal: modalConfirm,
- createModal: vi.fn(),
toast: { error: messageError, success: messageSuccess },
}));
-vi.mock('@lobehub/ui', async (importOriginal) => {
- const actual = await importOriginal<{ ErrorBoundary: typeof LobeErrorBoundary }>();
- return {
- Accordion: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- AccordionItem: ({ children, title }: { children?: ReactNode; title?: ReactNode }) => (
- <div>
- {title}
- {children}
- </div>
- ),
- ActionIcon: ({
- onClick,
- title,
- }: {
- onClick?: (e: React.MouseEvent) => void;
- title?: string;
- }) => (
- <button aria-label={title} onClick={onClick}>
- {title}
- </button>
- ),
- Center: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Empty: ({ description }: { description?: ReactNode }) => <div>{description}</div>,
- ErrorBoundary: actual.ErrorBoundary,
- Flexbox: ({
- children,
- onClick,
- ...props
- }: {
- children?: ReactNode;
- onClick?: () => void;
- [key: string]: unknown;
- }) => (
- <div onClick={onClick} {...props}>
- {children}
- </div>
- ),
- Highlighter: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Text: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- };
-});
-
vi.mock('@/components/NeuralNetworkLoading', () => ({
default: () => <div data-testid="neural-network-loading" />,
}));
diff --git a/src/features/Conversation/WorkingSidebar/Review/__tests__/FileItem.test.tsx b/src/features/Conversation/WorkingSidebar/Review/__tests__/FileItem.test.tsx
index ef99b4bc488..24af6c8eb91 100644
--- a/src/features/Conversation/WorkingSidebar/Review/__tests__/FileItem.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/Review/__tests__/FileItem.test.tsx
@@ -5,27 +5,11 @@ import { FileItemHeader } from '../FileItem';
const mockRevealInFilesTab = vi.fn();
-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
- return {
- ...actual,
- ActionIcon: ({ icon: _icon, title, onClick, ...rest }: any) => (
- <button aria-label={title} type="button" onClick={onClick} {...rest} />
- ),
- };
-});
-
vi.mock('@/store/global', () => ({
useGlobalStore: (selector: (s: any) => any) =>
selector({ revealInFilesTab: mockRevealInFilesTab }),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('@/components/AntdStaticMethods', () => ({
message: { error: vi.fn(), success: vi.fn() },
}));
diff --git a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
index e6813cd73d7..645ce45a9d3 100644
--- a/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
+++ b/src/features/Conversation/WorkingSidebar/__tests__/index.test.tsx
@@ -266,16 +266,11 @@ vi.mock('@/store/user/selectors', () => ({
labPreferSelectors: { enableInAppBrowser: () => true },
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
<button aria-label={title} type="button" onClick={onClick} />
),
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Icon: () => <span />,
Skeleton: () => <div data-testid="params-loading" />,
}));
diff --git a/src/features/Conversation/hooks/useAgentMeta.test.ts b/src/features/Conversation/hooks/useAgentMeta.test.ts
index db104bd0746..cf836bea6a9 100644
--- a/src/features/Conversation/hooks/useAgentMeta.test.ts
+++ b/src/features/Conversation/hooks/useAgentMeta.test.ts
@@ -7,8 +7,6 @@ import type * as ConversationStoreModule from '../store';
import { useConversationStore } from '../store';
import { useAgentMeta, useIsBuiltinAgent } from './useAgentMeta';
-vi.mock('zustand/traditional');
-
// Mock the ConversationStore
vi.mock('../store', async (importOriginal) => {
const actual = await importOriginal<typeof ConversationStoreModule>();
diff --git a/src/features/Conversation/hooks/useConversationResourceAccess.test.ts b/src/features/Conversation/hooks/useConversationResourceAccess.test.ts
index a869d9a9c74..6b6a5743bb3 100644
--- a/src/features/Conversation/hooks/useConversationResourceAccess.test.ts
+++ b/src/features/Conversation/hooks/useConversationResourceAccess.test.ts
@@ -27,10 +27,6 @@ vi.mock('@/features/ResourcePermission/useResourceAccess', () => ({
useResourceAccess: (...args: unknown[]) => mocks.useResourceAccess(...(args as [])),
}));
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/store/agent', () => ({
useAgentStore: (selector: (state: typeof mocks.agentState) => unknown) =>
selector(mocks.agentState),
diff --git a/src/features/DeleteTopicConfirm/index.test.tsx b/src/features/DeleteTopicConfirm/index.test.tsx
index 3443c68fd8e..bd79bc0e243 100644
--- a/src/features/DeleteTopicConfirm/index.test.tsx
+++ b/src/features/DeleteTopicConfirm/index.test.tsx
@@ -9,7 +9,8 @@ import { confirmRemoveTopic } from './index';
const confirmModalMock = vi.hoisted(() => vi.fn());
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
confirmModal: confirmModalMock,
}));
diff --git a/src/features/DesktopOnboarding/steps/LoginStep.test.tsx b/src/features/DesktopOnboarding/steps/LoginStep.test.tsx
index 6d955620263..2cea13ed2fa 100644
--- a/src/features/DesktopOnboarding/steps/LoginStep.test.tsx
+++ b/src/features/DesktopOnboarding/steps/LoginStep.test.tsx
@@ -1,8 +1,9 @@
import type { DataSyncConfig } from '@lobechat/electron-client-ipc';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import LoginStep from './LoginStep';
+
const mockElectronState = vi.hoisted(() => ({
clearRemoteServerSyncError: vi.fn(),
connectRemoteServer: vi.fn(),
@@ -19,56 +20,6 @@ vi.mock('@lobechat/electron-client-ipc', () => ({
useWatchBroadcast: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => {
- const Button = ({
- children,
- disabled,
- onClick,
- }: {
- children: ReactNode;
- disabled?: boolean;
- onClick?: () => void;
- }) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- );
-
- return {
- Alert: ({ description, title }: { description?: ReactNode; title?: ReactNode }) => (
- <section>
- <h2>{title}</h2>
- <p>{description}</p>
- </section>
- ),
- Button,
- Center: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Icon: () => <span />,
- Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
- Text: ({ as, children }: { as?: 'p' | 'span'; children: ReactNode }) =>
- as === 'p' ? <p>{children}</p> : <span>{children}</span>,
- };
-});
-
-vi.mock('antd', () => ({
- Divider: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}));
-
-vi.mock('antd-style', async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
-
- return {
- ...actual,
- createStaticStyles: () => ({}),
- cssVar: {
- colorFillSecondary: '#eee',
- colorTextDescription: '#888',
- colorTextSecondary: '#666',
- },
- };
-});
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, options?: string | Record<string, string>) => {
@@ -159,7 +110,6 @@ vi.mock('../components/LobeMessage', () => ({
}));
const renderLoginStep = async (props: { mode?: 'onboarding' | 'status' } = {}) => {
- const { default: LoginStep } = await import('./LoginStep');
const onBack = vi.fn();
const onNext = vi.fn();
diff --git a/src/features/EditorCanvas/DocumentIdMode.test.tsx b/src/features/EditorCanvas/DocumentIdMode.test.tsx
index 013c33143d8..4ea09383861 100644
--- a/src/features/EditorCanvas/DocumentIdMode.test.tsx
+++ b/src/features/EditorCanvas/DocumentIdMode.test.tsx
@@ -32,12 +32,6 @@ const mockDocumentStore = {
useFetchDocument,
};
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('zustand-utils', () => ({
createStoreUpdater: () => () => undefined,
}));
diff --git a/src/features/EditorCanvas/InternalEditor.readonly.test.tsx b/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
index 78453f981c1..d9d445c39c2 100644
--- a/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
+++ b/src/features/EditorCanvas/InternalEditor.readonly.test.tsx
@@ -39,14 +39,6 @@ vi.mock('@lobehub/editor', () => ({
ReactToolbarPlugin: vi.fn(),
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ onClick, title }: { onClick?: (e: any) => void; title?: string }) => (
- <button aria-label={title} onClick={onClick}>
- {title}
- </button>
- ),
-}));
-
vi.mock('@/features/ChatInput/InputEditor/plugins', () => ({
createChatInputRichPlugins: () => [],
}));
diff --git a/src/features/EditorCanvas/UnsavedChangesGuard.test.tsx b/src/features/EditorCanvas/UnsavedChangesGuard.test.tsx
index 88e470d97c4..821f5307364 100644
--- a/src/features/EditorCanvas/UnsavedChangesGuard.test.tsx
+++ b/src/features/EditorCanvas/UnsavedChangesGuard.test.tsx
@@ -11,17 +11,9 @@ const messageLoadingMock = vi.hoisted(() => vi.fn());
const messageDestroyMock = vi.hoisted(() => vi.fn());
const messageErrorMock = vi.hoisted(() => vi.fn());
-vi.mock('@lobehub/ui/base-ui', () => ({
- toast: {
- error: messageErrorMock,
- loading: messageLoadingMock,
- },
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ toast: { error: messageErrorMock, loading: messageLoadingMock },
}));
vi.mock('react-router', async () => {
diff --git a/src/features/EditorModal/index.test.ts b/src/features/EditorModal/index.test.ts
index a1022c0324b..8d6eef27478 100644
--- a/src/features/EditorModal/index.test.ts
+++ b/src/features/EditorModal/index.test.ts
@@ -3,11 +3,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { openEditorModal } from '.';
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: () => null,
- createModal: vi.fn(() => ({ close: vi.fn(), destroy: vi.fn(), update: vi.fn() })),
- ModalFooter: () => null,
- useModalContext: () => ({ close: vi.fn() }),
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
}));
vi.mock('./EditorModalContent', () => ({ default: () => null }));
diff --git a/src/features/Electron/AuthRequiredModal/index.test.tsx b/src/features/Electron/AuthRequiredModal/index.test.tsx
index b6f7becba4b..1151711f5bb 100644
--- a/src/features/Electron/AuthRequiredModal/index.test.tsx
+++ b/src/features/Electron/AuthRequiredModal/index.test.tsx
@@ -42,46 +42,13 @@ vi.mock('@lobechat/electron-client-ipc', () => ({
},
}));
-vi.mock('@lobehub/ui', () => ({
- Button: ({
- children,
- disabled,
- onClick,
- }: {
- children?: ReactNode;
- disabled?: boolean;
- onClick?: () => void;
- }) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- ),
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Icon: () => <span data-testid="modal-icon" />,
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: ({
- children,
- disabled,
- loading,
- onClick,
- }: {
- children?: ReactNode;
- disabled?: boolean;
- loading?: boolean;
- onClick?: () => void;
- }) => (
- <button disabled={disabled || loading} type="button" onClick={onClick}>
- {children}
- </button>
- ),
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
createModal: (props: ModalProps) => {
createModalMock(props);
return modalInstance;
},
- ModalFooter: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
}));
vi.mock('react-i18next', () => ({
diff --git a/src/features/Electron/system/ZoomHUD/index.test.tsx b/src/features/Electron/system/ZoomHUD/index.test.tsx
index e9357b52968..ab5476b267f 100644
--- a/src/features/Electron/system/ZoomHUD/index.test.tsx
+++ b/src/features/Electron/system/ZoomHUD/index.test.tsx
@@ -13,10 +13,6 @@ vi.mock('@lobechat/electron-client-ipc', () => ({
},
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('motion/react', async () => {
const React = await import('react');
return {
diff --git a/src/features/Electron/titlebar/NavigationBar.test.tsx b/src/features/Electron/titlebar/NavigationBar.test.tsx
index 4cbe7079d9a..c3fe350813a 100644
--- a/src/features/Electron/titlebar/NavigationBar.test.tsx
+++ b/src/features/Electron/titlebar/NavigationBar.test.tsx
@@ -1,5 +1,4 @@
import { act, render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import NavigationBar from './NavigationBar';
@@ -14,32 +13,11 @@ vi.mock('@lobechat/electron-client-ipc', () => ({
useWatchBroadcast: (event: string, handler: () => void) => mocks.handlers.set(event, handler),
}));
-vi.mock('@lobehub/ui', () => ({
- ActionIcon: ({ icon: _icon, ...props }: Record<string, unknown>) => <button {...props} />,
- Flexbox: ({ children, ...props }: { children: ReactNode }) => <div {...props}>{children}</div>,
- Popover: ({
- children,
- content,
- open,
- }: {
- children: ReactNode;
- content: ReactNode;
- open: boolean;
- }) => (
- <div>
- {children}
- {open && content}
- </div>
- ),
- Tooltip: ({ children }: { children: ReactNode }) => children,
-}));
-
vi.mock('antd-style', async (importOriginal) => ({
...(await importOriginal<object>()),
createStaticStyles: () => ({ clock: 'clock' }),
}));
-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('@/features/NavPanel/ToggleLeftPanelButton', () => ({ default: () => null }));
vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
useWorkspaceAwareNavigate: () => mocks.navigate,
diff --git a/src/features/ExplorerTree/view/ExplorerTree.test.tsx b/src/features/ExplorerTree/view/ExplorerTree.test.tsx
index 23822342cd9..f8e4dec05a0 100644
--- a/src/features/ExplorerTree/view/ExplorerTree.test.tsx
+++ b/src/features/ExplorerTree/view/ExplorerTree.test.tsx
@@ -1,6 +1,5 @@
import { AGENT_DOCUMENT_CATEGORY, CUSTOM_FOLDER_FILE_TYPE } from '@lobechat/const';
import { act, fireEvent, render, waitFor } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { useRef } from 'react';
import { MemoryRouter } from 'react-router';
import { describe, expect, it, vi } from 'vitest';
@@ -15,19 +14,6 @@ import ExplorerTree, { getItemPathFromEventPath } from './ExplorerTree';
const showContextMenu = vi.hoisted(() => vi.fn());
-vi.mock('@lobehub/ui', () => ({
- ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
- <button aria-label={title} onClick={onClick}>
- {title}
- </button>
- ),
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- genCdnUrl: () => '',
- Icon: () => <span />,
- showContextMenu,
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
-}));
-
vi.mock('@/libs/contextMenu', () => ({
showContextMenu,
}));
@@ -36,18 +22,8 @@ vi.mock('@lobehub/ui/icons', () => ({
SkillsIcon: () => null,
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ onClick, title }: { onClick?: () => void; title?: string }) => (
- <button aria-label={title} onClick={onClick}>
- {title}
- </button>
- ),
- confirmModal: vi.fn(),
- DropdownMenu: ({ children }: { children: ReactNode }) => children,
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
message: { error: vi.fn(), success: vi.fn(), warning: vi.fn() },
@@ -66,12 +42,6 @@ vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
useWorkspaceAwareNavigate: () => vi.fn(),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
const dispatchRealContextMenuEventRetargetedPastShadowRoot = (
shadowRow: HTMLElement,
shadowHost: Element,
diff --git a/src/features/FloatingChatPanel/ChatBody.test.tsx b/src/features/FloatingChatPanel/ChatBody.test.tsx
index fc3bbd24d0f..e1c37b039d8 100644
--- a/src/features/FloatingChatPanel/ChatBody.test.tsx
+++ b/src/features/FloatingChatPanel/ChatBody.test.tsx
@@ -2,39 +2,11 @@
* @vitest-environment happy-dom
*/
import { render, screen } from '@testing-library/react';
-import type { CSSProperties, ReactNode } from 'react';
+import type { ReactNode } from 'react';
import { describe, expect, it, vi } from 'vitest';
import ChatBody from './ChatBody';
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({
- children,
- flex,
- height,
- style,
- width,
- ...props
- }: {
- children?: ReactNode;
- flex?: number;
- height?: string;
- style?: CSSProperties;
- width?: string;
- [key: string]: unknown;
- }) => (
- <div
- data-flex={flex === undefined ? '' : String(flex)}
- data-height={height ?? ''}
- data-width={width ?? ''}
- style={style}
- {...props}
- >
- {children}
- </div>
- ),
-}));
-
vi.mock('@/features/Conversation', () => ({
ChatList: ({ welcome }: { welcome?: ReactNode }) => (
<div data-testid="floating-chat-list">
@@ -54,8 +26,8 @@ describe('FloatingChatPanel ChatBody', () => {
const body = screen.getByTestId('floating-chat-panel-body');
const list = screen.getByTestId('floating-chat-list');
- expect(body).toHaveAttribute('data-flex', '1');
- expect(body).toHaveAttribute('data-height', '100%');
+ expect(body.style.getPropertyValue('--lobe-flex')).toBe('1');
+ expect(body.style.getPropertyValue('--lobe-flex-height')).toBe('100%');
expect(body).toContainElement(list);
expect(list).toContainElement(screen.getByTestId('agent-welcome'));
expect(body).toHaveStyle({ overflow: 'hidden' });
diff --git a/src/features/FloatingChatPanel/InputRow.test.tsx b/src/features/FloatingChatPanel/InputRow.test.tsx
index 9993023ab23..eea8df832bb 100644
--- a/src/features/FloatingChatPanel/InputRow.test.tsx
+++ b/src/features/FloatingChatPanel/InputRow.test.tsx
@@ -45,10 +45,6 @@ vi.mock('@/features/Conversation/store', () => ({
selector(mockConversationState.current),
}));
-vi.mock('@lobehub/ui', () => ({
- Icon: ({ icon }: { icon: () => void }) => <span data-testid="icon">{icon.name}</span>,
-}));
-
describe('FloatingChatPanel InputRow', () => {
it('does not render the expand affordance when disabled', () => {
render(<InputRow isCollapsed={false} showExpandBar={false} onExpand={() => {}} />);
diff --git a/src/features/FloatingChatPanel/index.test.tsx b/src/features/FloatingChatPanel/index.test.tsx
index 0b4307117eb..b49f3c9fbfa 100644
--- a/src/features/FloatingChatPanel/index.test.tsx
+++ b/src/features/FloatingChatPanel/index.test.tsx
@@ -16,7 +16,8 @@ const sheetHandlers = vi.hoisted(() => ({
},
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
ActionIcon: ({
onClick,
title,
@@ -77,28 +78,6 @@ vi.mock('@lobehub/ui/base-ui', () => ({
},
}));
-vi.mock('@lobehub/ui', () => ({
- ActionIcon: ({
- onClick,
- title,
- ...rest
- }: {
- onClick?: () => void;
- title?: string;
- [key: string]: unknown;
- }) => (
- <button
- data-testid={(rest as any)['data-testid']}
- title={title}
- type="button"
- onClick={onClick}
- >
- {title}
- </button>
- ),
- Icon: ({ icon }: { icon: () => void }) => <span data-icon={icon.name} />,
-}));
-
const mergedHooksCaptured = vi.hoisted(() => ({
current: undefined as
| undefined
diff --git a/src/features/Home/AgentSelect/useHomeAgentRows.test.ts b/src/features/Home/AgentSelect/useHomeAgentRows.test.ts
index 5743f267d1c..7147eef8e68 100644
--- a/src/features/Home/AgentSelect/useHomeAgentRows.test.ts
+++ b/src/features/Home/AgentSelect/useHomeAgentRows.test.ts
@@ -26,10 +26,6 @@ const mocks = vi.hoisted(() => ({
sidebarVisibilityOverrides: {} as Record<string, boolean>,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => mocks.activeWorkspaceId,
}));
diff --git a/src/features/Home/InputArea/useSend.test.ts b/src/features/Home/InputArea/useSend.test.ts
index 3d7547750c4..df87152a706 100644
--- a/src/features/Home/InputArea/useSend.test.ts
+++ b/src/features/Home/InputArea/useSend.test.ts
@@ -91,11 +91,8 @@ const activeWorkspaceIdMock = vi.hoisted(() => ({
value: null as string | null,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
toast: { error: messageErrorMock },
}));
diff --git a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
index 67e6bb37794..89de4f494b6 100644
--- a/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
+++ b/src/features/HomeSidebar/Body/Agent/List/AgentItem/useDropdownMenu.test.tsx
@@ -41,11 +41,8 @@ vi.mock('antd', async (importOriginal) => {
};
});
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
confirmModal: mocks.confirmModal,
toast: { error: mocks.toastError, success: vi.fn() },
}));
diff --git a/src/features/HomeSidebar/Body/Agent/List/Group/useDropdownMenu.test.ts b/src/features/HomeSidebar/Body/Agent/List/Group/useDropdownMenu.test.ts
index 13607cdb590..c469f794015 100644
--- a/src/features/HomeSidebar/Body/Agent/List/Group/useDropdownMenu.test.ts
+++ b/src/features/HomeSidebar/Body/Agent/List/Group/useDropdownMenu.test.ts
@@ -12,23 +12,10 @@ vi.mock('@lobehub/ui', () => ({
Icon: () => null,
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- confirmModal: vi.fn(),
- toast: { error: vi.fn(), success: vi.fn() },
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => null,
}));
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/libs/trpc/client', () => ({
lambdaClient: {},
}));
diff --git a/src/features/HomeSidebar/Body/Agent/useDropdownMenu.test.tsx b/src/features/HomeSidebar/Body/Agent/useDropdownMenu.test.tsx
index 7b498921a8e..d650a43f39b 100644
--- a/src/features/HomeSidebar/Body/Agent/useDropdownMenu.test.tsx
+++ b/src/features/HomeSidebar/Body/Agent/useDropdownMenu.test.tsx
@@ -12,12 +12,6 @@ vi.mock('@lobehub/ui', () => ({
Icon: () => null,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('@/features/HomeSidebar/Body/CustomizeSidebarModal', () => ({
openCustomizeSidebarModal: vi.fn(),
}));
diff --git a/src/features/HomeSidebar/Body/index.test.tsx b/src/features/HomeSidebar/Body/index.test.tsx
index e23265956ac..2612b05b434 100644
--- a/src/features/HomeSidebar/Body/index.test.tsx
+++ b/src/features/HomeSidebar/Body/index.test.tsx
@@ -21,7 +21,8 @@ const mocks = vi.hoisted(() => ({
updateSystemStatus: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Accordion: ({
children,
expandedKeys,
@@ -36,16 +37,9 @@ vi.mock('@lobehub/ui', () => ({
{children}
</div>
),
- ActionIcon: () => <span />,
- DropdownMenu: ({ children }: { children: React.ReactNode }) => <>{children}</>,
Flexbox: ({ children }: { children: React.ReactNode }) => (
<div data-testid="sidebar-body">{children}</div>
),
- Icon: () => <span />,
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock('react-router', () => ({
diff --git a/src/features/HomeSidebar/Footer/index.test.tsx b/src/features/HomeSidebar/Footer/index.test.tsx
index ce649a1709b..cdfb9094321 100644
--- a/src/features/HomeSidebar/Footer/index.test.tsx
+++ b/src/features/HomeSidebar/Footer/index.test.tsx
@@ -6,27 +6,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
const analyticsTrack = vi.fn();
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({
- onClick,
- title,
- ...rest
- }: {
- onClick?: (e: any) => void;
- title?: string;
- [key: string]: unknown;
- }) => (
- <button
- aria-label={(rest as any)['aria-label'] ?? title}
- title={title}
- type="button"
- onClick={onClick}
- >
- {title}
- </button>
- ),
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
i18n: { language: 'en-US' },
diff --git a/src/features/HomeSidebar/hooks/useCreateMenuItems.test.tsx b/src/features/HomeSidebar/hooks/useCreateMenuItems.test.tsx
index 79220ce585e..9e915b81c71 100644
--- a/src/features/HomeSidebar/hooks/useCreateMenuItems.test.tsx
+++ b/src/features/HomeSidebar/hooks/useCreateMenuItems.test.tsx
@@ -25,17 +25,8 @@ vi.mock('@lobechat/const', () => ({
isDesktop: true,
}));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
- Icon: () => null,
- Text: ({ children }: { children?: React.ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('@lobehub/ui/icons', () => ({
- GroupBotSquareIcon: () => null,
-}));
-
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
message: { error: messageErrorMock },
@@ -44,12 +35,6 @@ vi.mock('antd', () => ({
},
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('react-router', () => ({
useNavigate: () => navigateMock,
}));
diff --git a/src/features/HomeSidebar/hooks/useCreateModal.test.tsx b/src/features/HomeSidebar/hooks/useCreateModal.test.tsx
index fbe8fc9749a..edb4211607a 100644
--- a/src/features/HomeSidebar/hooks/useCreateModal.test.tsx
+++ b/src/features/HomeSidebar/hooks/useCreateModal.test.tsx
@@ -51,15 +51,8 @@ vi.mock('@lobehub/analytics', () => ({
}),
}));
-vi.mock('@lobehub/ui', () => ({
- ActionIcon: ({ onClick }: { onClick?: () => void }) => (
- <button aria-label="icon action" type="button" onClick={onClick} />
- ),
- Block: ({ children, onClick }: { children?: ReactNode; onClick?: () => void }) => (
- <button type="button" onClick={onClick}>
- {children}
- </button>
- ),
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Button: ({
children,
disabled,
@@ -83,8 +76,6 @@ vi.mock('@lobehub/ui', () => ({
{children}
</button>
),
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
}));
vi.mock('@/services/marketApi', () => ({
@@ -99,13 +90,8 @@ vi.mock('@/services/skill', () => ({
},
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ onClick, title }: { onClick?: (e: React.MouseEvent) => void; title?: string }) => (
- <button aria-label={title} onClick={onClick}>
- {title}
- </button>
- ),
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Button: ({
children,
disabled,
@@ -132,17 +118,6 @@ vi.mock('@lobehub/ui/base-ui', () => ({
createModal: vi.fn(),
}));
-vi.mock('antd-style', () => ({
- cssVar: {
- borderRadiusLG: 8,
- colorError: '#f00',
- colorSuccess: '#0a0',
- colorTextDescription: '#666',
- colorTextSecondary: '#666',
- colorTextTertiary: '#999',
- },
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: (namespace: string) => ({
t: (key: string) =>
diff --git a/src/features/Messenger/IntegrationDetail/Wechat.test.tsx b/src/features/Messenger/IntegrationDetail/Wechat.test.tsx
index 51c1d24638d..891f2e4ab19 100644
--- a/src/features/Messenger/IntegrationDetail/Wechat.test.tsx
+++ b/src/features/Messenger/IntegrationDetail/Wechat.test.tsx
@@ -13,49 +13,8 @@ const messengerServiceMocks = vi.hoisted(() => ({
}));
const useSWRMock = vi.hoisted(() => vi.fn());
-vi.mock('@lobehub/ui', () => ({
- Alert: ({ message }: { message?: ReactNode }) => <div>{message}</div>,
- Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Icon: () => <span />,
- Input: ({
- disabled,
- onChange,
- placeholder,
- value,
- }: {
- disabled?: boolean;
- onChange?: (event: { target: { value: string } }) => void;
- placeholder?: string;
- value?: string;
- }) => (
- <input
- disabled={disabled}
- placeholder={placeholder}
- value={value}
- onChange={(event) => onChange?.(event)}
- />
- ),
- Skeleton: { Button: () => <span>Loading</span> },
- Tag: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
-}));
-
vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
- ...((await importOriginal()) as Record<string, unknown>),
- Button: ({
- children,
- disabled,
- onClick,
- }: {
- children?: ReactNode;
- disabled?: boolean;
- onClick?: () => void;
- }) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- ),
+ ...(await importOriginal<object>()),
Select: ({
onChange,
options,
@@ -73,12 +32,10 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
))}
</select>
),
- Tag: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
- toast: { error: vi.fn(), info: vi.fn(), success: vi.fn(), warning: vi.fn() },
}));
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
QRCode: ({
'aria-label': ariaLabel,
bgColor,
@@ -145,7 +102,6 @@ vi.mock('@/components/NeuralNetworkLoading', () => ({ default: () => <span>Loadi
vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
useWorkspaceAwareNavigate: () => vi.fn(),
}));
-vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
vi.mock('@/services/messenger', () => ({ messengerService: messengerServiceMocks }));
vi.mock('../i18n', () => ({ getMessengerErrorMessage: () => 'error' }));
vi.mock('./shared', () => ({
diff --git a/src/features/Messenger/IntegrationDetail/shared.test.tsx b/src/features/Messenger/IntegrationDetail/shared.test.tsx
index 209850a5218..cb0bc20ac7f 100644
--- a/src/features/Messenger/IntegrationDetail/shared.test.tsx
+++ b/src/features/Messenger/IntegrationDetail/shared.test.tsx
@@ -16,54 +16,10 @@ const userState = {
},
};
-vi.mock('@lobehub/ui', () => ({
- Avatar: ({ avatar }: { avatar?: string }) => <span data-avatar={avatar} />,
- Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Button: ({ children, onClick }: { children?: ReactNode; onClick?: () => void }) => (
- <button onClick={onClick}>{children}</button>
- ),
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Icon: () => <span />,
- Skeleton: () => <span />,
- Tag: ({ children }: { children?: ReactNode }) => (
- <span data-testid="personal-tag">{children}</span>
- ),
- Text: ({
- children,
- ellipsis,
- }: {
- children?: ReactNode;
- ellipsis?: boolean | { tooltip?: boolean | string };
- }) => (
- <span
- title={
- typeof ellipsis === 'object' && typeof ellipsis.tooltip === 'string'
- ? ellipsis.tooltip
- : undefined
- }
- >
- {children}
- </span>
- ),
-}));
-
const mockConfirmModal = vi.fn();
-vi.mock('@lobehub/ui/base-ui', () => ({
- Avatar: ({ avatar }: { avatar?: string }) => <span data-avatar={avatar} />,
- Button: ({
- children,
- disabled,
- onClick,
- }: {
- children?: ReactNode;
- disabled?: boolean;
- onClick?: () => void;
- }) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- ),
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Select: ({
classNames,
options,
@@ -102,13 +58,8 @@ vi.mock('@lobehub/ui/base-ui', () => ({
confirmModal: (...args: unknown[]) => mockConfirmModal(...args),
}));
-vi.mock('antd', () => ({
- App: {
- useApp: () => ({ message: { error: vi.fn(), success: vi.fn() } }),
- },
-}));
-
-vi.mock('antd-style', () => ({
+vi.mock('antd-style', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
createStaticStyles: () => ({
backButton: 'backButton',
card: 'card',
@@ -145,10 +96,6 @@ vi.mock('swr', () => ({
}),
}));
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/services/messenger', () => ({
messengerService: {
listBindingScopes: vi.fn(),
diff --git a/src/features/ModelSwitchPanel/components/BenchmarkModal/index.test.tsx b/src/features/ModelSwitchPanel/components/BenchmarkModal/index.test.tsx
index d1eefd7e2a8..d9040138c8c 100644
--- a/src/features/ModelSwitchPanel/components/BenchmarkModal/index.test.tsx
+++ b/src/features/ModelSwitchPanel/components/BenchmarkModal/index.test.tsx
@@ -8,7 +8,8 @@ import { describe, expect, it, vi } from 'vitest';
import BenchmarkModalContent from './index';
-vi.mock('antd-style', () => ({
+vi.mock('antd-style', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
createStaticStyles: () =>
new Proxy({}, { get: (_target, prop: string) => prop }) as Record<string, string>,
cssVar: new Proxy({}, { get: (_target, token) => `var(--${String(token)})` }),
@@ -29,20 +30,8 @@ vi.mock('@lobehub/charts', () => ({
),
}));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children, ...props }: { children?: ReactNode }) => {
- const {
- horizontal: _h,
- align: _a,
- justify: _j,
- gap: _g,
- paddingBlock: _p,
- ...rest
- } = props as any;
-
- return <div {...rest}>{children}</div>;
- },
- Icon: () => <span />,
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Tooltip: ({ children, title }: { children: ReactNode; title?: ReactNode }) => (
<span>
<span data-testid={'tooltip'}>{title}</span>
@@ -57,7 +46,8 @@ interface MockMenuItem {
onClick: () => void;
}
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
createModal: vi.fn(),
DropdownMenu: ({ children, items }: { children: ReactNode; items: MockMenuItem[] }) => (
<div>
diff --git a/src/features/ModelSwitchPanel/components/ControlsForm/__tests__/ControlsForm.test.tsx b/src/features/ModelSwitchPanel/components/ControlsForm/__tests__/ControlsForm.test.tsx
index b4ec4186af3..89f55566056 100644
--- a/src/features/ModelSwitchPanel/components/ControlsForm/__tests__/ControlsForm.test.tsx
+++ b/src/features/ModelSwitchPanel/components/ControlsForm/__tests__/ControlsForm.test.tsx
@@ -27,21 +27,22 @@ const testState = vi.hoisted(() => ({
updateAgentChatConfig: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => {
+vi.mock('@lobehub/ui', async (importOriginal) => {
const MockForm = () => <div data-testid="controls-form" />;
MockForm.useForm = () => [{ setFieldsValue: testState.setFieldsValue }];
return {
- Flexbox: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
+ ...(await importOriginal<object>()),
Form: MockForm,
};
});
-vi.mock('antd', () => {
+vi.mock('antd', async (importOriginal) => {
+ const antd = await importOriginal<{ Form: object }>();
+
return {
- Form: { useWatch: vi.fn(() => undefined) },
- Grid: { useBreakpoint: () => ({ sm: true }) },
- Switch: () => <input type="checkbox" />,
+ ...antd,
+ Form: { ...antd.Form, useWatch: vi.fn(() => undefined) },
};
});
diff --git a/src/features/ModelSwitchPanel/components/List/__tests__/MultipleProvidersModelItem.test.tsx b/src/features/ModelSwitchPanel/components/List/__tests__/MultipleProvidersModelItem.test.tsx
index ef5aa4609ca..4e9ebf0f23c 100644
--- a/src/features/ModelSwitchPanel/components/List/__tests__/MultipleProvidersModelItem.test.tsx
+++ b/src/features/ModelSwitchPanel/components/List/__tests__/MultipleProvidersModelItem.test.tsx
@@ -9,13 +9,8 @@ import type * as ModelSelectModule from '@/components/ModelSelect';
import { MultipleProvidersModelItem } from '../MultipleProvidersModelItem';
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
DropdownMenuGroup: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DropdownMenuGroupLabel: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DropdownMenuItem: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
@@ -39,15 +34,9 @@ vi.mock('@lobehub/ui', () => ({
{children}
</div>
),
- Flexbox: ({ children, ...props }: HTMLAttributes<HTMLDivElement>) => (
- <div {...props}>{children}</div>
- ),
- Icon: () => <span />,
- Tag: ({ children }: { children: ReactNode }) => <span>{children}</span>,
Tooltip: ({ children, title }: { children: ReactNode; title: string }) => (
<span data-testid={`tooltip-${title}`}>{children}</span>
),
- menuSharedStyles: { item: 'item' },
}));
vi.mock('@lobehub/ui/base-ui', () => ({
diff --git a/src/features/ModelSwitchPanel/components/ModelDetailPanel.test.tsx b/src/features/ModelSwitchPanel/components/ModelDetailPanel.test.tsx
index 5853b0cb234..92323b4d423 100644
--- a/src/features/ModelSwitchPanel/components/ModelDetailPanel.test.tsx
+++ b/src/features/ModelSwitchPanel/components/ModelDetailPanel.test.tsx
@@ -3,7 +3,6 @@
*/
import { render, screen } from '@testing-library/react';
import type { ModelRating } from 'model-bank';
-import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { EnabledProviderWithModels } from '@/types/aiProvider';
@@ -45,39 +44,6 @@ vi.mock('./BenchmarkModal', () => ({
openBenchmarkModal: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => ({
- Accordion: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- AccordionItem: ({
- action,
- children,
- title,
- }: {
- action?: ReactNode;
- children?: ReactNode;
- title?: ReactNode;
- }) => (
- <section>
- <div>{title}</div>
- <div>{action}</div>
- <div>{children}</div>
- </section>
- ),
- Flexbox: ({ children, ...props }: { children?: ReactNode }) => <div {...props}>{children}</div>,
- Icon: () => <span />,
- Tag: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- Text: ({ children, ...props }: { children: ReactNode }) => {
- const { type: _type, ...rest } = props as Record<string, unknown>;
-
- return <p {...rest}>{children}</p>;
- },
- Tooltip: ({ children, title }: { children: ReactNode; title?: ReactNode }) => (
- <span>
- {title}
- {children}
- </span>
- ),
-}));
-
vi.mock('@/hooks/useEnabledChatModels', () => ({
useEnabledChatModels: () => [],
}));
@@ -90,7 +56,7 @@ vi.mock('@/business/client/hooks/useBusinessModelRating', () => ({
const globalState = {
status: {
- modelDetailPanelExpandedKeys: ['pricing'],
+ modelDetailPanelExpandedKeys: ['pricing', 'rating'],
},
updateModelDetailPanelExpandedKeys: vi.fn(),
};
@@ -415,7 +381,7 @@ describe('ModelDetailPanel rating', () => {
);
expect(container).toHaveTextContent('Benchmarks');
- expect(container.querySelector('svg')).toBeInTheDocument();
+ expect(container.querySelector('[data-testid="radar-chart"]')).toBeInTheDocument();
expect(container).toHaveTextContent('Intelligence');
expect(container).toHaveTextContent('100');
// agentic has no data: the dimension is omitted from the radar entirely
@@ -438,7 +404,7 @@ describe('ModelDetailPanel rating', () => {
);
expect(container).toHaveTextContent('Benchmarks');
- expect(container.querySelector('svg')).not.toBeInTheDocument();
+ expect(container.querySelector('[data-testid="radar-chart"]')).not.toBeInTheDocument();
expect(container).toHaveTextContent('Intelligence');
expect(container).toHaveTextContent('91');
// unrated dimensions are not listed in the fallback view
diff --git a/src/features/ModelSwitchPanel/components/ModelRatingRadar.test.tsx b/src/features/ModelSwitchPanel/components/ModelRatingRadar.test.tsx
index dfac4f072ee..bbd5872f2c7 100644
--- a/src/features/ModelSwitchPanel/components/ModelRatingRadar.test.tsx
+++ b/src/features/ModelSwitchPanel/components/ModelRatingRadar.test.tsx
@@ -7,12 +7,6 @@ import { describe, expect, it, vi } from 'vitest';
import type { RadarDimensionDatum } from './ModelRatingRadar';
import ModelRatingRadar, { RATING_DIMENSION_ORDER } from './ModelRatingRadar';
-vi.mock('antd-style', () => ({
- createStaticStyles: () =>
- new Proxy({}, { get: (_target, prop: string) => prop }) as Record<string, string>,
- cssVar: new Proxy({}, { get: (_target, token) => `var(--${String(token)})` }),
-}));
-
const { radarChartProps } = vi.hoisted(() => ({ radarChartProps: vi.fn() }));
vi.mock('@lobehub/charts', () => ({
diff --git a/src/features/Onboarding/Classic/index.test.tsx b/src/features/Onboarding/Classic/index.test.tsx
index 8765adfacfd..67799ede952 100644
--- a/src/features/Onboarding/Classic/index.test.tsx
+++ b/src/features/Onboarding/Classic/index.test.tsx
@@ -22,10 +22,6 @@ const mocks = vi.hoisted(() => ({
setOnboardingStep: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}));
-
vi.mock('@/components/Loading/BrandTextLoading', () => ({
default: ({ debugId }: { debugId: string }) => <div>Loading:{debugId}</div>,
}));
diff --git a/src/features/Onboarding/steps/AgentPickerStep/index.test.tsx b/src/features/Onboarding/steps/AgentPickerStep/index.test.tsx
index 9aaae148cd8..0adc619bc0b 100644
--- a/src/features/Onboarding/steps/AgentPickerStep/index.test.tsx
+++ b/src/features/Onboarding/steps/AgentPickerStep/index.test.tsx
@@ -11,17 +11,6 @@ import AgentPickerStep from './index';
// base-ui Button needs a MotionProvider the app wires globally but the unit env
// lacks; stub it to a native button so the assertions can run.
-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
- return {
- ...actual,
- Button: ({ children, disabled, onClick }: any) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- ),
- };
-});
const navigate = vi.fn();
const finishOnboarding = vi.fn().mockResolvedValue(undefined);
diff --git a/src/features/Onboarding/steps/InterestsStep.test.tsx b/src/features/Onboarding/steps/InterestsStep.test.tsx
index ab0c2336283..914555c4d9b 100644
--- a/src/features/Onboarding/steps/InterestsStep.test.tsx
+++ b/src/features/Onboarding/steps/InterestsStep.test.tsx
@@ -1,6 +1,5 @@
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import type { MouseEventHandler, ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import InterestsStep from './InterestsStep';
@@ -10,51 +9,6 @@ const mocks = vi.hoisted(() => ({
updateInterests: vi.fn(),
}));
-// base-ui Button needs a MotionProvider the app wires globally but the unit env
-// lacks; stub it to a native button so the assertions can run.
-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
- return {
- ...actual,
- Button: ({ children, disabled, onClick }: any) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- ),
- };
-});
-
-vi.mock('@lobehub/ui', () => ({
- Block: ({
- children,
- onClick,
- }: {
- children: ReactNode;
- onClick?: MouseEventHandler<HTMLButtonElement>;
- }) => (
- <button type="button" onClick={onClick}>
- {children}
- </button>
- ),
- Button: ({
- children,
- disabled,
- onClick,
- }: {
- children: ReactNode;
- disabled?: boolean;
- onClick?: MouseEventHandler<HTMLButtonElement>;
- }) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- ),
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Icon: () => null,
- Input: () => null,
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string) =>
@@ -107,7 +61,7 @@ describe('InterestsStep', () => {
render(<InterestsStep onBack={vi.fn()} onNext={onNext} />);
- await user.click(screen.getByRole('button', { name: '内容创作' }));
+ await user.click(screen.getByText('内容创作'));
await user.click(screen.getByRole('button', { name: 'Next' }));
expect(mocks.updateInterests).toHaveBeenCalledWith(['writing']);
diff --git a/src/features/Onboarding/steps/ProSettingsStep.test.tsx b/src/features/Onboarding/steps/ProSettingsStep.test.tsx
index da793af386e..4d8f7500c02 100644
--- a/src/features/Onboarding/steps/ProSettingsStep.test.tsx
+++ b/src/features/Onboarding/steps/ProSettingsStep.test.tsx
@@ -1,36 +1,8 @@
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
-import type { MouseEventHandler, ReactNode } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import ProSettingsStep from './ProSettingsStep';
-// base-ui Button needs a MotionProvider the app wires globally but the unit env
-// lacks; stub it to a native button so the assertions can run.
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: ({ children, disabled, onClick }: any) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- ),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Button: ({
- children,
- disabled,
- onClick,
- }: {
- children: ReactNode;
- disabled?: boolean;
- onClick?: MouseEventHandler<HTMLButtonElement>;
- }) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- ),
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string) =>
diff --git a/src/features/OpenInAppButton/index.test.tsx b/src/features/OpenInAppButton/index.test.tsx
index da570035dd8..27d36b9d52e 100644
--- a/src/features/OpenInAppButton/index.test.tsx
+++ b/src/features/OpenInAppButton/index.test.tsx
@@ -30,7 +30,8 @@ vi.mock('react-i18next', () => ({
}),
}));
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
DropdownMenu: ({
children,
items,
@@ -71,38 +72,6 @@ vi.mock('@lobehub/ui', () => ({
),
}));
-vi.mock('antd-style', () => ({
- createStaticStyles: () => ({
- dropdownItem: 'dropdownItem',
- leftButton: 'leftButton',
- rightButton: 'rightButton',
- root: 'root',
- }),
- cssVar: new Proxy({}, { get: () => 'var(--placeholder)' }),
-}));
-
-vi.mock('lucide-react', () => {
- const Stub = () => null;
- return {
- AppleIcon: Stub,
- ChevronDownIcon: Stub,
- CodeIcon: Stub,
- CodeXmlIcon: Stub,
- FolderIcon: Stub,
- FolderOpenIcon: Stub,
- GhostIcon: Stub,
- HammerIcon: Stub,
- SquareTerminalIcon: Stub,
- TerminalIcon: Stub,
- };
-});
-
-vi.mock('@lobehub/icons', () => ({
- Cursor: function Cursor() {
- return null;
- },
-}));
-
beforeEach(() => {
isDesktopValue = true;
launchMock.mockReset();
diff --git a/src/features/OpenInAppButton/useOpenInApp.test.tsx b/src/features/OpenInAppButton/useOpenInApp.test.tsx
index 06340c2bb00..3e48a79b26b 100644
--- a/src/features/OpenInAppButton/useOpenInApp.test.tsx
+++ b/src/features/OpenInAppButton/useOpenInApp.test.tsx
@@ -9,6 +9,11 @@ const wrapper = ({ children }: { children: ReactNode }) => (
<SWRConfig value={{ dedupingInterval: 0, provider: () => new Map() }}>{children}</SWRConfig>
);
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
+}));
+
vi.mock('@lobechat/const', () => ({
isDesktop: true,
}));
@@ -20,10 +25,6 @@ vi.mock('@/services/electron/openInApp', () => ({
},
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- toast: { error: vi.fn() },
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, opts?: Record<string, unknown>) =>
diff --git a/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.test.tsx b/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.test.tsx
index 15eec8480f5..3760007588b 100644
--- a/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.test.tsx
+++ b/src/features/PageEditor/Copilot/TopicSelector/useDropdownMenu.test.tsx
@@ -13,21 +13,12 @@ const permissionMock = vi.hoisted(() => ({
edit_own_content: true,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Icon: () => null,
-}));
-
vi.mock('@/features/DeleteTopicConfirm', () => ({
confirmRemoveTopic: confirmRemoveTopicMock,
}));
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
message: {
diff --git a/src/features/PageEditor/Header/useMenu.test.tsx b/src/features/PageEditor/Header/useMenu.test.tsx
index 1165b0d39b1..b4bd18c72e5 100644
--- a/src/features/PageEditor/Header/useMenu.test.tsx
+++ b/src/features/PageEditor/Header/useMenu.test.tsx
@@ -38,15 +38,12 @@ vi.mock('@lobechat/const', () => ({
isDesktop: false,
}));
-vi.mock('@lobehub/ui', () => ({
- Icon: () => null,
-}));
-
vi.mock('@lobehub/ui/base-ui', () => ({
confirmModal: vi.fn(),
}));
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
message: {
@@ -60,16 +57,6 @@ vi.mock('antd', () => ({
},
}));
-vi.mock('antd-style', () => ({
- createStaticStyles: () => ({}),
- cssVar: {
- colorTextTertiary: 'colorTextTertiary',
- },
- cx: (...args: unknown[]) => args.filter(Boolean).join(' '),
- keyframes: () => '',
- useResponsive: () => ({ lg: true }),
-}));
-
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => resourcePermissionMock.workspaceId,
}));
diff --git a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsx b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsx
index 72a1d042e47..b7bcbf234f0 100644
--- a/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsx
+++ b/src/features/Pages/PageLayout/Body/List/Item/useDropdownMenu.test.tsx
@@ -21,17 +21,8 @@ const storeMock = vi.hoisted(() => ({
{ id: string; userId?: string; visibility?: 'private' | 'public' | null } | undefined,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Icon: () => null,
-}));
-
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
message: {
diff --git a/src/features/Portal/AcceptanceCheck/Body.test.tsx b/src/features/Portal/AcceptanceCheck/Body.test.tsx
index 83aa3d905b9..8fd5220fb63 100644
--- a/src/features/Portal/AcceptanceCheck/Body.test.tsx
+++ b/src/features/Portal/AcceptanceCheck/Body.test.tsx
@@ -9,9 +9,8 @@ const mocks = vi.hoisted(() => ({
mutate: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => ({
- Center: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Empty: () => <div />,
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Flexbox: ({
children,
className,
@@ -29,21 +28,6 @@ vi.mock('@lobehub/ui', () => ({
</div>
),
Icon: () => <span data-testid={'check-state-icon'} />,
- Tag: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
- ...(await importOriginal<object>()),
- ...(await import('~base-ui-stubs')).baseUiStubs,
-}));
-
-vi.mock('antd', () => ({
- App: { useApp: () => ({ message: { error: vi.fn() } }) },
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock('@/store/chat', () => ({
diff --git a/src/features/Portal/Artifacts/Body/index.test.tsx b/src/features/Portal/Artifacts/Body/index.test.tsx
index 038fbda77e5..5d5accf138b 100644
--- a/src/features/Portal/Artifacts/Body/index.test.tsx
+++ b/src/features/Portal/Artifacts/Body/index.test.tsx
@@ -19,7 +19,8 @@ const mockArtifactState = vi.hoisted(() => ({
setState: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Flexbox: ({ children, style }: { children: ReactNode; style?: CSSProperties }) => (
<div data-testid={style?.overflow === 'auto' ? 'artifact-scroll-container' : undefined}>
{children}
diff --git a/src/features/Portal/Document/Body.test.tsx b/src/features/Portal/Document/Body.test.tsx
index 10424d5f02d..c644aaa0e07 100644
--- a/src/features/Portal/Document/Body.test.tsx
+++ b/src/features/Portal/Document/Body.test.tsx
@@ -1,5 +1,4 @@
import { act, fireEvent, render, screen } from '@testing-library/react';
-import { type ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import DocumentBody from './Body';
@@ -21,20 +20,6 @@ vi.mock('antd-style', async (importOriginal) => {
};
});
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- ActionIcon: () => null,
- Button: ({ children }: { children: ReactNode }) => <button>{children}</button>,
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
- TextArea: () => <textarea />,
-}));
-
vi.mock('@/components/CodeEditorPane', () => ({
default: ({
onChange,
diff --git a/src/features/Portal/LocalFile/Body.test.tsx b/src/features/Portal/LocalFile/Body.test.tsx
index 590ac6470f9..33f127e83e9 100644
--- a/src/features/Portal/LocalFile/Body.test.tsx
+++ b/src/features/Portal/LocalFile/Body.test.tsx
@@ -29,28 +29,6 @@ vi.mock('antd-style', async (importOriginal) => ({
},
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Center: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Empty: ({ description }: { description?: ReactNode }) => <div>{description}</div>,
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Icon: () => null,
- Image: ({ alt, src }: { alt?: string; src?: string }) => <img alt={alt} src={src} />,
- Markdown: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
- ...((await importOriginal()) as Record<string, unknown>),
- ActionIcon: () => null,
- Tabs: () => null,
-}));
-
vi.mock('@/components/CodeEditorPane', () => ({
default: () => <textarea data-testid="code-editor" />,
}));
diff --git a/src/features/Portal/LocalFile/MarkdownImage.test.tsx b/src/features/Portal/LocalFile/MarkdownImage.test.tsx
index 41d6d96c666..bd6deb4d67c 100644
--- a/src/features/Portal/LocalFile/MarkdownImage.test.tsx
+++ b/src/features/Portal/LocalFile/MarkdownImage.test.tsx
@@ -41,12 +41,6 @@ vi.mock('@lobehub/ui', () => ({
},
}));
-vi.mock('antd-style', () => ({
- cssVar: {
- colorFillQuaternary: 'var(--color-fill-quaternary)',
- },
-}));
-
vi.mock('@/libs/swr', () => ({
useClientDataSWR: mockUseClientDataSWR,
}));
diff --git a/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.test.ts b/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.test.ts
index c6e379cbb80..aeedc8417a8 100644
--- a/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.test.ts
+++ b/src/features/Portal/LocalFile/prepareWorkspaceHtmlPublish.test.ts
@@ -10,7 +10,8 @@ const readWorkspaceAsset = vi.hoisted(() => vi.fn());
const toastError = vi.hoisted(() => vi.fn());
const toastSuccess = vi.hoisted(() => vi.fn());
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
toast: { error: toastError, success: toastSuccess },
}));
diff --git a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsx b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsx
index 2f582ca5ae8..d0df5dadad8 100644
--- a/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsx
+++ b/src/features/ProfileEditor/AgentUserTools/UserToolsSection.test.tsx
@@ -35,10 +35,6 @@ const mocks = vi.hoisted(() => ({
},
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
// Personal vs workspace only changes the label, not the count under test.
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => 'ws-1',
@@ -49,12 +45,12 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
vi.mock('@/features/ProfileEditor/AgentTool', () => ({ default: () => null }));
vi.mock('@/features/ProfileEditor/PluginTag', () => ({ default: () => null }));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Text: ({ children }: { children: ReactNode }) => <span data-testid="label">{children}</span>,
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: ({ children }: { children: ReactNode }) => <button type="button">{children}</button>,
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Text: ({ children }: { children: ReactNode }) => <span data-testid="label">{children}</span>,
}));
diff --git a/src/features/ProfileEditor/PluginTag.test.tsx b/src/features/ProfileEditor/PluginTag.test.tsx
index e57a9075027..1bf9d9c8b8e 100644
--- a/src/features/ProfileEditor/PluginTag.test.tsx
+++ b/src/features/ProfileEditor/PluginTag.test.tsx
@@ -44,11 +44,9 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
...(await importOriginal<object>()),
Avatar: ({ title }: { title?: string }) => <span data-testid="author-avatar">{title}</span>,
}));
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Avatar: ({ title }: { title?: string }) => <span data-testid="author-avatar">{title}</span>,
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Icon: () => null,
- Tag: ({ children }: { children: ReactNode }) => <div>{children}</div>,
Tooltip: ({ children, title }: { children: ReactNode; title?: string }) => (
<div data-testid="author-tooltip" data-title={title}>
{children}
diff --git a/src/features/RecommendTaskTemplates/ConnectorAuthRow.test.tsx b/src/features/RecommendTaskTemplates/ConnectorAuthRow.test.tsx
index c564a9f5495..7d7969ca100 100644
--- a/src/features/RecommendTaskTemplates/ConnectorAuthRow.test.tsx
+++ b/src/features/RecommendTaskTemplates/ConnectorAuthRow.test.tsx
@@ -22,10 +22,6 @@ vi.mock('./providerMeta', () => ({
getProviderMeta: () => ({ icon: 'https://example.com/icon.png', label: 'HubSpot' }),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
describe('ConnectorAuthRow', () => {
beforeEach(() => {
connectMock.mockReset();
diff --git a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts
index 42433edb8af..2a72909ff30 100644
--- a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts
+++ b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts
@@ -36,7 +36,8 @@ vi.mock('ahooks', () => ({
useSessionStorageState: () => ['', mockSetRefreshSeed],
}));
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({ message: { error: vi.fn() } }),
},
diff --git a/src/features/RecommendTaskTemplates/useResolvedInterestKeys.test.ts b/src/features/RecommendTaskTemplates/useResolvedInterestKeys.test.ts
index 369e133c89f..de13320bd9d 100644
--- a/src/features/RecommendTaskTemplates/useResolvedInterestKeys.test.ts
+++ b/src/features/RecommendTaskTemplates/useResolvedInterestKeys.test.ts
@@ -1,13 +1,11 @@
import { act, renderHook } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
import { useUserStore } from '@/store/user';
import type { LobeUser } from '@/types/user';
import { useResolvedInterestKeys } from './useResolvedInterestKeys';
-vi.mock('zustand/traditional');
-
describe('useResolvedInterestKeys', () => {
it('returns null before auth loads', () => {
const { result } = renderHook(() => useResolvedInterestKeys());
diff --git a/src/features/ResourceHome/Layout/Body/LibraryList/Item/index.test.tsx b/src/features/ResourceHome/Layout/Body/LibraryList/Item/index.test.tsx
index 4efd690fa1f..1b5fda6378a 100644
--- a/src/features/ResourceHome/Layout/Body/LibraryList/Item/index.test.tsx
+++ b/src/features/ResourceHome/Layout/Body/LibraryList/Item/index.test.tsx
@@ -34,10 +34,6 @@ vi.mock('@/features/NavPanel/OverlayContainer', () => ({
useOverlayPopoverPortalProps: () => undefined,
}));
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/features/ResourceManager/store', () => ({
useResourceManagerStore: (selector: (state: { setLibraryId: () => void }) => unknown) =>
selector({ setLibraryId: vi.fn() }),
diff --git a/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.test.ts b/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.test.ts
index 4769b34330b..d455242fa80 100644
--- a/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.test.ts
+++ b/src/features/ResourceHome/Layout/Body/LibraryList/Item/useDropdownMenu.test.ts
@@ -18,19 +18,10 @@ const mocks = vi.hoisted(() => ({
],
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@lobehub/ui', () => ({
Icon: () => null,
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- confirmModal: vi.fn(),
- toast: { error: vi.fn(), success: vi.fn() },
-}));
-
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => mocks.activeWorkspaceId,
}));
diff --git a/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.test.tsx b/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.test.tsx
index d5864e04e3a..dfcf9b2e951 100644
--- a/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.test.tsx
+++ b/src/features/ResourceManager/components/Explorer/EmptyPlaceholder.test.tsx
@@ -14,12 +14,6 @@ let category: FilesTabs = FilesTabs.All;
let libraryId: string | undefined;
let sourceFilter: ResourceSourceFilter | undefined;
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('@/features/LibraryModal', () => ({
useCreateNewModal: () => ({ open: mockOpen }),
}));
diff --git a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx
index fd251cbaed7..7043ce6b998 100644
--- a/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx
+++ b/src/features/ResourceManager/components/Explorer/ItemDropdown/useFileItemDropdown.test.tsx
@@ -13,9 +13,7 @@ const mocks = vi.hoisted(() => ({
vi.mock('@/features/Messenger/PushResourceModal/useSendToMessengerMenuItem', () => ({
useSendToMessengerMenuItem: mocks.useSendToMessengerMenuItem,
}));
-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('@/hooks/useAppOrigin', () => ({ useAppOrigin: () => 'https://app.example.com' }));
-vi.mock('@/hooks/usePermission', () => ({ usePermission: () => ({ allowed: true }) }));
vi.mock('@/hooks/useResourceManageable', () => ({ useResourceManageable: () => true }));
vi.mock('@/features/ResourceManager/components/KnowledgeBaseListProvider', () => ({
useKnowledgeBaseListContext: () => [],
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts
index ebdc06e1c2b..b75b2d547b4 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/FileListItemActions.test.ts
@@ -13,10 +13,6 @@ vi.mock('@/business/client/hooks/useFileTransferMenuItem', () => ({
useFileTransferMenuItem: mocks.useFileTransferMenuItem,
}));
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('../../ItemDropdown/DropdownMenu', () => ({
default: () => null,
}));
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.test.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.test.tsx
index 9529fc05a56..4688a18e81a 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.test.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListItem/index.test.tsx
@@ -1,33 +1,12 @@
import { render, screen } from '@testing-library/react';
-import type { CSSProperties, ReactNode } from 'react';
import { describe, expect, it, vi } from 'vitest';
import FileListItem from './index';
-vi.mock('@lobehub/ui', () => {
- const Box = ({ children, className, style, ...props }: any) => {
- const domProps = Object.fromEntries(
- Object.entries(props).filter(([key]) => key.startsWith('data-') || key.startsWith('aria-')),
- );
-
- return (
- <div className={className} style={style as CSSProperties} {...domProps}>
- {children}
- </div>
- );
- };
-
- return {
- Avatar: ({ alt }: { alt: string }) => <span data-testid="avatar">{alt}</span>,
- Center: Box,
- Checkbox: ({ checked, disabled }: { checked?: boolean; disabled?: boolean }) => (
- <input readOnly checked={checked} disabled={disabled} type="checkbox" />
- ),
- ContextMenuTrigger: ({ children }: { children: ReactNode }) => <>{children}</>,
- Flexbox: Box,
- Tooltip: ({ children }: { children: ReactNode }) => <>{children}</>,
- };
-});
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ Avatar: ({ alt }: { alt: string }) => <span data-testid="avatar">{alt}</span>,
+}));
vi.mock('react-i18next', () => ({
useTranslation: () => ({
diff --git a/src/features/ResourceManager/components/Explorer/ListView/ListViewHeader.test.tsx b/src/features/ResourceManager/components/Explorer/ListView/ListViewHeader.test.tsx
index c801c6c8543..416a490add4 100644
--- a/src/features/ResourceManager/components/Explorer/ListView/ListViewHeader.test.tsx
+++ b/src/features/ResourceManager/components/Explorer/ListView/ListViewHeader.test.tsx
@@ -9,23 +9,6 @@ const selectionMocks = vi.hoisted(() => ({
handleSelectAllResources: vi.fn(),
}));
-vi.mock('@lobehub/ui', async () => {
- const actual = await vi.importActual<Record<string, unknown>>('@lobehub/ui');
-
- return {
- ...actual,
- Checkbox: ({ onChange }: { onChange?: (checked: boolean) => void }) => (
- <button role="checkbox" type="button" onClick={() => onChange?.(true)} />
- ),
- };
-});
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('@/store/global', () => ({
useGlobalStore: (
selector: (state: {
diff --git a/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsx b/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsx
index 4de59b9b58a..19a2fb950c1 100644
--- a/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsx
+++ b/src/features/ResourcePermission/ResourceConfigAccessGate.test.tsx
@@ -12,8 +12,10 @@ const mocks = vi.hoisted(() => ({
toastInfo: vi.fn(),
}));
-vi.mock('@lobehub/ui/base-ui', () => ({ toast: { info: mocks.toastInfo } }));
-vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ toast: { info: mocks.toastInfo },
+}));
vi.mock('@/components/AsyncBoundary', () => ({
default: ({
children,
diff --git a/src/features/ResourcePermission/useAccessLevelOptions.test.ts b/src/features/ResourcePermission/useAccessLevelOptions.test.ts
index 570b4b93d21..6464d6193a6 100644
--- a/src/features/ResourcePermission/useAccessLevelOptions.test.ts
+++ b/src/features/ResourcePermission/useAccessLevelOptions.test.ts
@@ -1,13 +1,9 @@
import { renderHook } from '@testing-library/react';
import { EyeIcon, LockIcon, PlayIcon } from 'lucide-react';
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
import { useAccessLevelOptions } from './useAccessLevelOptions';
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
describe('useAccessLevelOptions', () => {
it('uses access and lock icons for knowledge-base visibility levels', () => {
const { result } = renderHook(() =>
diff --git a/src/features/ResourcePermission/useAgentManagementAccess.test.tsx b/src/features/ResourcePermission/useAgentManagementAccess.test.tsx
index d55dd637a9d..445860378f5 100644
--- a/src/features/ResourcePermission/useAgentManagementAccess.test.tsx
+++ b/src/features/ResourcePermission/useAgentManagementAccess.test.tsx
@@ -17,10 +17,6 @@ vi.mock('@/features/ResourcePermission/useResourceAccess', () => ({
useResourceAccess: () => testState.permission,
}));
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/store/agent', () => ({
useAgentStore: (selector: (state: { agentMap: Record<string, unknown> }) => unknown) =>
selector({ agentMap: testState.agent ? { 'agent-1': testState.agent } : {} }),
diff --git a/src/features/ResourcePermission/useResourceCollaborators.test.ts b/src/features/ResourcePermission/useResourceCollaborators.test.ts
index 4283d865676..f62b1ab9caa 100644
--- a/src/features/ResourcePermission/useResourceCollaborators.test.ts
+++ b/src/features/ResourcePermission/useResourceCollaborators.test.ts
@@ -15,6 +15,11 @@ const swrState = vi.hoisted(() => ({
mutate: vi.fn(),
}));
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
+}));
+
vi.mock('@/services/resourcePermission', () => ({
resourcePermissionService: serviceMocks,
}));
@@ -26,8 +31,6 @@ vi.mock('@/libs/swr', () => ({
},
}));
-vi.mock('@lobehub/ui/base-ui', () => ({ toast: { error: vi.fn() } }));
-
describe('useResourceCollaborators', () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/src/features/Settings/Layout/Body/activeTab.desktop.test.ts b/src/features/Settings/Layout/Body/activeTab.desktop.test.ts
index 14eb28e77a3..a5c75364939 100644
--- a/src/features/Settings/Layout/Body/activeTab.desktop.test.ts
+++ b/src/features/Settings/Layout/Body/activeTab.desktop.test.ts
@@ -46,14 +46,6 @@ vi.mock('react-router', () => ({
Link: ({ children }: { children?: ReactNode }) => h('span', null, children),
}));
-vi.mock('@lobehub/ui', () => ({
- Accordion: ({ children }: { children?: ReactNode }) => h('div', null, children),
- AccordionItem: ({ children, title }: { children?: ReactNode; title?: ReactNode }) =>
- h('div', null, title, children),
- Flexbox: ({ children }: { children?: ReactNode }) => h('div', null, children),
- Text: ({ children }: { children?: ReactNode }) => h('span', null, children),
-}));
-
const tab = (id: string, url: string) => ({ id, lastVisited: 0, url });
const activeStateOf = (label: string) =>
diff --git a/src/features/Settings/apikey/features/ApiKey.test.tsx b/src/features/Settings/apikey/features/ApiKey.test.tsx
index c7349a93a31..334079f0cb4 100644
--- a/src/features/Settings/apikey/features/ApiKey.test.tsx
+++ b/src/features/Settings/apikey/features/ApiKey.test.tsx
@@ -1,6 +1,5 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
-import type { ButtonHTMLAttributes, ReactNode } from 'react';
import { SWRConfig } from 'swr';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -29,82 +28,11 @@ const hoisted = vi.hoisted(() => ({
toast: { error: vi.fn(), success: vi.fn(), warning: vi.fn() },
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
+ toast: hoisted.toast,
}));
-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
-
- return {
- ...actual,
- Button: ({ children, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) => (
- <button {...props}>{children}</button>
- ),
- Checkbox: ({
- checked,
- children,
- disabled,
- onChange,
- }: {
- checked?: boolean;
- children?: ReactNode;
- disabled?: boolean;
- onChange?: (checked: boolean) => void;
- }) => (
- <label>
- <input
- checked={checked}
- disabled={disabled}
- type="checkbox"
- onChange={(event) => onChange?.(event.currentTarget.checked)}
- />
- {children}
- </label>
- ),
- Drawer: ({
- children,
- onClose,
- open,
- title,
- }: {
- children?: ReactNode;
- onClose?: () => void;
- open?: boolean;
- title?: ReactNode;
- }) =>
- open ? (
- <div role="dialog">
- <div>{title}</div>
- <button type="button" onClick={onClose}>
- close-drawer
- </button>
- {children}
- </div>
- ) : null,
- Switch: ({
- checked,
- disabled,
- onChange,
- }: {
- checked?: boolean;
- disabled?: boolean;
- onChange?: (checked: boolean) => void;
- children?: ReactNode;
- }) => (
- <input
- checked={checked}
- disabled={disabled}
- role="switch"
- type="checkbox"
- onChange={(event) => onChange?.(event.currentTarget.checked)}
- />
- ),
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
- toast: hoisted.toast,
- };
-});
-
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
getActiveWorkspaceId: () => hoisted.state.activeWorkspaceId,
useActiveWorkspaceId: () => hoisted.state.activeWorkspaceId,
@@ -345,7 +273,11 @@ describe('ApiKey', () => {
const dialog = await openDetail('My Key');
fireEvent.click(within(dialog).getByRole('switch'));
- await waitFor(() => expect(hoisted.toast.error).toHaveBeenCalledWith('manageOnlyCreator'));
+ await waitFor(() =>
+ expect(hoisted.toast.error).toHaveBeenCalledWith(
+ 'Only the creator or a workspace owner can do this',
+ ),
+ );
expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(1);
});
@@ -357,7 +289,9 @@ describe('ApiKey', () => {
const dialog = await openDetail('My Key');
fireEvent.click(within(dialog).getByRole('switch'));
- await waitFor(() => expect(hoisted.toast.error).toHaveBeenCalledWith('operationFailed'));
+ await waitFor(() =>
+ expect(hoisted.toast.error).toHaveBeenCalledWith('Operation failed, please try again'),
+ );
expect(hoisted.trpc.getApiKeys).toHaveBeenCalledTimes(1);
});
@@ -531,9 +465,14 @@ describe('ApiKey', () => {
const dialog = await openDetail('My Key');
fireEvent.click(within(dialog).getByRole('button', { name: 'apikey.detail.permissions.edit' }));
- const scopeCheckboxes = within(dialog).getAllByRole('checkbox');
- fireEvent.click(scopeCheckboxes[0]);
- fireEvent.click(scopeCheckboxes[2]);
+ const toggleScope = (groupKey: string) => {
+ const group = within(dialog).getByText(`apikey.scopes.groups.${groupKey}`).parentElement!;
+ const checkbox = within(group).getByRole('checkbox', { name: 'apikey.scopes.read' });
+ fireEvent.keyDown(checkbox, { key: ' ' });
+ fireEvent.keyUp(checkbox, { key: ' ' });
+ };
+ toggleScope('agent');
+ toggleScope('chat');
fireEvent.click(within(dialog).getByRole('button', { name: 'apikey.detail.permissions.save' }));
await waitFor(() =>
diff --git a/src/features/Settings/hooks/useCategory.test.tsx b/src/features/Settings/hooks/useCategory.test.tsx
index 6a6a2f7f811..be532f89400 100644
--- a/src/features/Settings/hooks/useCategory.test.tsx
+++ b/src/features/Settings/hooks/useCategory.test.tsx
@@ -20,12 +20,6 @@ vi.hoisted(() => {
});
});
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
const createWrapper = (showProvider: boolean) => {
const Wrapper = ({ children }: { children: ReactNode }) => (
<Provider
diff --git a/src/features/Settings/labs/index.test.tsx b/src/features/Settings/labs/index.test.tsx
index bf818268d52..ee590c96d05 100644
--- a/src/features/Settings/labs/index.test.tsx
+++ b/src/features/Settings/labs/index.test.tsx
@@ -23,55 +23,13 @@ vi.mock('@lobechat/const', async (importOriginal) => ({
isDesktop: true,
}));
-vi.mock('antd-style', () => ({
- createStaticStyles: () => ({
- labItem: 'lab-item',
- }),
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Form: ({
- items,
- }: {
- items: {
- children: { children?: ReactNode; desc?: string; label: string }[];
- title: string;
- }[];
- }) => (
- <div>
- {items.map((group) => (
- <section key={group.title}>
- <h2>{group.title}</h2>
- {group.children.map((item) => (
- <div key={item.label}>
- <span>{item.label}</span>
- {item.children}
- </div>
- ))}
- </section>
- ))}
- </div>
- ),
- Skeleton: () => <div>loading</div>,
- Tag: ({ children }: { children: ReactNode }) => <span>{children}</span>,
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Tooltip: ({ children, title }: { children: ReactNode; title: string }) => (
<span title={title}>{children}</span>
),
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- Alert: ({ title }: { title: ReactNode }) => <div role={'note'}>{title}</div>,
- Switch: () => <button />,
- Tag: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
vi.mock('@/features/Settings/features/SettingHeader', () => ({
default: ({ description, title }: { description?: string; title: string }) => (
<header>
@@ -111,7 +69,7 @@ describe('Labs settings page', () => {
// The page title comes from the settings shell header (like Plans / Storage),
// so the experimental notice has to carry itself as a standalone banner.
- expect(screen.getByRole('note').textContent).toBe('description');
+ expect(screen.getByRole('alert').textContent).toBe('description');
});
it('hides its own setting header when the shell renders a compact one', () => {
@@ -119,7 +77,7 @@ describe('Labs settings page', () => {
render(<Page showSettingHeader={false} />, { wrapper: createWrapper() });
expect(screen.queryByRole('heading', { level: 1 })).toBeNull();
- expect(screen.getByRole('note').textContent).toBe('description');
+ expect(screen.getByRole('alert').textContent).toBe('description');
});
it('splits experiments into General and Desktop groups', () => {
diff --git a/src/features/Settings/memory/features/Memory.test.tsx b/src/features/Settings/memory/features/Memory.test.tsx
index 6cbd3e38426..998b16fe9db 100644
--- a/src/features/Settings/memory/features/Memory.test.tsx
+++ b/src/features/Settings/memory/features/Memory.test.tsx
@@ -2,8 +2,6 @@
* @vitest-environment happy-dom
*/
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
-import type { FormInstance } from 'antd';
-import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import MemorySetting from './Memory';
@@ -11,14 +9,6 @@ import MemorySetting from './Memory';
const setSettingsMock = vi.hoisted(() => vi.fn());
const memorySettingsMock = vi.hoisted(() => ({ value: {} as { enabled?: boolean } }));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/hooks/useSaveState', () => ({
useSaveState: () => ({
lastSavedAt: undefined,
@@ -44,66 +34,6 @@ vi.mock('@/features/ModelSwitchPanel/components/ControlsForm/LevelSlider', () =>
default: () => null,
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- Switch: ({
- checked,
- disabled,
- onChange,
- }: {
- checked?: boolean;
- disabled?: boolean;
- onChange?: (checked: boolean) => void;
- }) => (
- <button
- aria-checked={!!checked}
- disabled={disabled}
- role="switch"
- onClick={() => onChange?.(!checked)}
- />
- ),
-}));
-
-vi.mock('@lobehub/ui', async () => {
- const { Form: AntdForm } = await import('antd');
-
- const Form = Object.assign(
- ({
- form,
- initialValues,
- items,
- onValuesChange,
- }: {
- form?: FormInstance<Record<string, unknown>>;
- initialValues: Record<string, unknown>;
- items: Array<{
- children: Array<{ children: ReactNode; name?: string; valuePropName?: string }>;
- }>;
- onValuesChange: (values: Record<string, unknown>) => void;
- }) => (
- <AntdForm form={form} initialValues={initialValues} onValuesChange={onValuesChange}>
- {items.flatMap((group) =>
- group.children.flatMap((item) => {
- if (!item.name) return [];
-
- return [
- <AntdForm.Item key={item.name} name={item.name} valuePropName={item.valuePropName}>
- {item.children}
- </AntdForm.Item>,
- ];
- }),
- )}
- </AntdForm>
- ),
- { useForm: AntdForm.useForm },
- );
-
- return {
- Form,
- Skeleton: () => null,
- Tooltip: ({ children }: { children: ReactNode }) => children,
- };
-});
-
describe('MemorySetting', () => {
afterEach(cleanup);
diff --git a/src/features/Settings/oauth-apps/index.test.tsx b/src/features/Settings/oauth-apps/index.test.tsx
index 245b7e50eaa..014ce8debeb 100644
--- a/src/features/Settings/oauth-apps/index.test.tsx
+++ b/src/features/Settings/oauth-apps/index.test.tsx
@@ -1,5 +1,4 @@
import { cleanup, render, screen } from '@testing-library/react';
-import { type ReactNode } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { useUserStore } from '@/store/user';
@@ -17,18 +16,10 @@ vi.hoisted(() => {
});
});
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('react-router', () => ({
useParams: () => ({}),
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: ({ children }: { children: ReactNode }) => <button>{children}</button>,
-}));
-
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => null,
}));
@@ -41,10 +32,6 @@ vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
useWorkspaceAwareNavigate: () => vi.fn(),
}));
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/libs/trpc/client', () => ({
lambdaClient: { oauthApp: { create: { mutate: vi.fn() } } },
}));
diff --git a/src/features/Settings/profile/features/InterestsRow.test.tsx b/src/features/Settings/profile/features/InterestsRow.test.tsx
index 56254f1d90c..73d59c6441d 100644
--- a/src/features/Settings/profile/features/InterestsRow.test.tsx
+++ b/src/features/Settings/profile/features/InterestsRow.test.tsx
@@ -1,6 +1,6 @@
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import type { MouseEventHandler, ReactNode } from 'react';
+import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import InterestsRow from './InterestsRow';
@@ -11,24 +11,6 @@ const mocks = vi.hoisted(() => ({
updateInterests: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => ({
- Block: ({
- children,
- onClick,
- }: {
- children: ReactNode;
- onClick?: MouseEventHandler<HTMLButtonElement>;
- }) => (
- <button type="button" onClick={onClick}>
- {children}
- </button>
- ),
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Icon: () => null,
- Input: () => null,
- Text: ({ children }: { children: ReactNode }) => <span>{children}</span>,
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: (namespace: string) => ({
t: (key: string) => {
@@ -97,7 +79,7 @@ describe('InterestsRow', () => {
render(<InterestsRow />);
- await user.click(screen.getByRole('button', { name: '编程与开发' }));
+ await user.click(screen.getByText('编程与开发'));
await waitFor(() => {
expect(mocks.updateInterests).toHaveBeenCalledWith(['coding']);
@@ -110,7 +92,7 @@ describe('InterestsRow', () => {
render(<InterestsRow />);
- await user.click(screen.getByRole('button', { name: '编程与开发' }));
+ await user.click(screen.getByText('编程与开发'));
await waitFor(() => {
expect(mocks.updateInterests).toHaveBeenCalledWith(['自定义']);
@@ -124,7 +106,7 @@ describe('InterestsRow', () => {
render(<InterestsRow />);
- await user.click(screen.getByRole('button', { name: '编程与开发' }));
+ await user.click(screen.getByText('编程与开发'));
await waitFor(() => {
expect(mocks.saveToast).toHaveBeenCalledWith(failure, {
@@ -141,7 +123,7 @@ describe('InterestsRow', () => {
render(<InterestsRow />);
- await user.click(screen.getByRole('button', { name: '编程与开发' }));
+ await user.click(screen.getByText('编程与开发'));
await waitFor(() => expect(mocks.saveToast).toHaveBeenCalled());
diff --git a/src/features/Settings/profile/features/usePasswordReset.test.ts b/src/features/Settings/profile/features/usePasswordReset.test.ts
index d4b001cdb51..3fe23f3acd6 100644
--- a/src/features/Settings/profile/features/usePasswordReset.test.ts
+++ b/src/features/Settings/profile/features/usePasswordReset.test.ts
@@ -8,10 +8,6 @@ const mocks = vi.hoisted(() => ({
saveToast: vi.fn(),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/libs/better-auth/auth-client', () => ({
requestPasswordReset: mocks.requestPasswordReset,
}));
diff --git a/src/features/Settings/provider/features/ModelList/ModelTitle/Search.test.tsx b/src/features/Settings/provider/features/ModelList/ModelTitle/Search.test.tsx
index eea0e35d34c..7dfb76cbc4f 100644
--- a/src/features/Settings/provider/features/ModelList/ModelTitle/Search.test.tsx
+++ b/src/features/Settings/provider/features/ModelList/ModelTitle/Search.test.tsx
@@ -3,23 +3,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import Search from './Search';
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- SearchBar: ({ onInputChange, value, ...props }: any) => (
- <input
- {...props}
- data-testid="search-input"
- value={value}
- onChange={(event) => onInputChange(event.target.value)}
- />
- ),
-}));
-
describe('ModelList Search', () => {
beforeEach(() => {
vi.useFakeTimers();
@@ -31,7 +14,7 @@ describe('ModelList Search', () => {
render(<Search value="abc" onChange={onChange} />);
- fireEvent.change(screen.getByTestId('search-input'), { target: { value: '' } });
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: '' } });
expect(onChange).toHaveBeenCalledWith('');
});
@@ -40,7 +23,7 @@ describe('ModelList Search', () => {
const onChange = vi.fn();
const { rerender } = render(<Search value="abc" onChange={onChange} />);
- fireEvent.change(screen.getByTestId('search-input'), { target: { value: 'abcd' } });
+ fireEvent.change(screen.getByRole('textbox'), { target: { value: 'abcd' } });
rerender(<Search value="" onChange={onChange} />);
diff --git a/src/features/Settings/provider/features/ModelList/SearchResult.test.tsx b/src/features/Settings/provider/features/ModelList/SearchResult.test.tsx
index 1002a0f25fc..f5abde6bc92 100644
--- a/src/features/Settings/provider/features/ModelList/SearchResult.test.tsx
+++ b/src/features/Settings/provider/features/ModelList/SearchResult.test.tsx
@@ -1,5 +1,4 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { type ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import SearchResult from './SearchResult';
@@ -9,15 +8,6 @@ const mocks = vi.hoisted(() => ({
canManageProvider: false,
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ onClick, title }: { onClick?: (e: any) => void; title?: string }) => (
- <button aria-label={title} onClick={onClick}>
- {title}
- </button>
- ),
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, values?: Record<string, unknown>) =>
diff --git a/src/features/Settings/proxy/features/ProxyForm.test.tsx b/src/features/Settings/proxy/features/ProxyForm.test.tsx
index a499f000eb9..90f95dc443f 100644
--- a/src/features/Settings/proxy/features/ProxyForm.test.tsx
+++ b/src/features/Settings/proxy/features/ProxyForm.test.tsx
@@ -3,16 +3,10 @@
*/
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import type { FormInstance } from 'antd';
-import type { ComponentProps, ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import ProxyForm from './ProxyForm';
-interface MockFormValues {
- [key: string]: unknown;
-}
-
const setProxySettingsMock = vi.hoisted(() => vi.fn());
const testProxyConfigMock = vi.hoisted(() => vi.fn());
const toastErrorMock = vi.hoisted(() => vi.fn());
@@ -27,12 +21,6 @@ const defaultProxySettings = {
proxyType: 'http',
} as const;
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('@/services/electron/settings', () => ({
desktopSettingsService: {
testProxyConfig: testProxyConfigMock,
@@ -74,138 +62,14 @@ vi.mock('./SaveBar', () => ({
) : null,
}));
-// Stub the base-ui Button (test-connection) to a native button — it needs a
-// MotionProvider the app sets up globally but the unit env doesn't. Keep
-// type="button" to match the real Button's default htmlType and avoid
-// implicitly submitting the surrounding form.
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: ({
- children,
- disabled,
- onClick,
- }: {
- children?: ReactNode;
- disabled?: boolean;
- onClick?: () => void;
- }) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- ),
- RadioGroup: ({
- disabled,
- onChange,
- options,
- value,
- }: {
- disabled?: boolean;
- onChange?: (value: string) => void;
- options?: Array<string | { disabled?: boolean; label?: ReactNode; value: string }>;
- value?: string;
- }) => (
- <div role="radiogroup">
- {options?.map((option) => {
- const item = typeof option === 'string' ? { label: option, value: option } : option;
- return (
- <label key={item.value}>
- <input
- checked={value === item.value}
- disabled={disabled || item.disabled}
- type="radio"
- value={item.value}
- onChange={() => onChange?.(item.value)}
- />
- {item.label}
- </label>
- );
- })}
- </div>
- ),
- Switch: ({
- checked,
- disabled,
- onChange,
- }: {
- checked?: boolean;
- disabled?: boolean;
- onChange?: (checked: boolean) => void;
- }) => (
- <button
- aria-checked={!!checked}
- disabled={disabled}
- role="switch"
- type="button"
- onClick={() => onChange?.(!checked)}
- />
- ),
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
toast: {
error: toastErrorMock,
success: toastSuccessMock,
},
}));
-vi.mock('@lobehub/ui', async () => {
- const { Form: AntdForm } = await import('antd');
-
- const GroupedForm = Object.assign(
- ({
- form,
- initialValues,
- items,
- onValuesChange,
- }: {
- form?: FormInstance<MockFormValues>;
- initialValues?: MockFormValues;
- items: Array<{
- children: Array<{
- children: ReactNode;
- label?: ReactNode;
- name?: string;
- rules?: ComponentProps<typeof AntdForm.Item>['rules'];
- valuePropName?: string;
- }>;
- }>;
- onValuesChange?: (changedValues: MockFormValues, values: MockFormValues) => void;
- }) => (
- <AntdForm form={form} initialValues={initialValues} onValuesChange={onValuesChange}>
- {items.map((group, groupIndex) => (
- <div key={groupIndex}>
- {group.children.map((item, itemIndex) =>
- item.name ? (
- <AntdForm.Item
- key={`${groupIndex}-${item.name}-${itemIndex}`}
- label={item.label}
- name={item.name}
- rules={item.rules}
- valuePropName={item.valuePropName}
- >
- {item.children}
- </AntdForm.Item>
- ) : (
- <div key={`${groupIndex}-${itemIndex}`}>
- {item.label ? <div>{item.label}</div> : null}
- {item.children}
- </div>
- ),
- )}
- </div>
- ))}
- </AntdForm>
- ),
- { useForm: AntdForm.useForm },
- );
-
- return {
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Form: GroupedForm,
- Skeleton: () => <div>loading</div>,
- toast: {
- error: toastErrorMock,
- success: toastSuccessMock,
- },
- };
-});
-
describe('ProxyForm', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -265,14 +129,14 @@ describe('ProxyForm', () => {
render(<ProxyForm />);
await user.click(screen.getAllByRole('switch')[0]);
- await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');
- await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '7890');
+ await user.type(screen.getByPlaceholderText('127.0.0.1'), '127.0.0.1');
+ await user.type(screen.getByPlaceholderText('7890'), '7890');
await user.click(screen.getByRole('button', { name: 'proxy.resetButton' }));
await waitFor(() => {
expect(screen.queryByRole('button', { name: 'proxy.resetButton' })).not.toBeInTheDocument();
- expect(screen.getByRole('textbox', { name: 'proxy.server' })).toHaveValue('');
- expect(screen.getByRole('textbox', { name: 'proxy.port' })).toHaveValue('');
+ expect(screen.getByPlaceholderText('127.0.0.1')).toHaveValue('');
+ expect(screen.getByPlaceholderText('7890')).toHaveValue('');
});
});
@@ -282,8 +146,8 @@ describe('ProxyForm', () => {
render(<ProxyForm />);
await user.click(screen.getAllByRole('switch')[0]);
- await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');
- await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '7890');
+ await user.type(screen.getByPlaceholderText('127.0.0.1'), '127.0.0.1');
+ await user.type(screen.getByPlaceholderText('7890'), '7890');
await user.click(screen.getAllByRole('switch')[1]);
expect(screen.getByPlaceholderText('proxy.username_placeholder')).toBeInTheDocument();
@@ -304,8 +168,8 @@ describe('ProxyForm', () => {
render(<ProxyForm />);
await user.click(screen.getAllByRole('switch')[0]);
- await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');
- await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '70000');
+ await user.type(screen.getByPlaceholderText('127.0.0.1'), '127.0.0.1');
+ await user.type(screen.getByPlaceholderText('7890'), '70000');
await user.click(screen.getByRole('button', { name: 'proxy.saveButton' }));
await waitFor(() => {
@@ -320,8 +184,8 @@ describe('ProxyForm', () => {
render(<ProxyForm />);
await user.click(screen.getAllByRole('switch')[0]);
- await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');
- await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '7890');
+ await user.type(screen.getByPlaceholderText('127.0.0.1'), '127.0.0.1');
+ await user.type(screen.getByPlaceholderText('7890'), '7890');
await user.click(screen.getByRole('button', { name: 'proxy.saveButton' }));
await waitFor(() => {
@@ -342,8 +206,8 @@ describe('ProxyForm', () => {
render(<ProxyForm />);
await user.click(screen.getAllByRole('switch')[0]);
- await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');
- await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '7890');
+ await user.type(screen.getByPlaceholderText('127.0.0.1'), '127.0.0.1');
+ await user.type(screen.getByPlaceholderText('7890'), '7890');
setProxySettingsMock.mockRejectedValueOnce(new Error('boom'));
@@ -363,8 +227,8 @@ describe('ProxyForm', () => {
render(<ProxyForm />);
await user.click(screen.getAllByRole('switch')[0]);
- await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');
- await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '7890');
+ await user.type(screen.getByPlaceholderText('127.0.0.1'), '127.0.0.1');
+ await user.type(screen.getByPlaceholderText('7890'), '7890');
await user.click(screen.getByRole('button', { name: 'proxy.testButton' }));
await waitFor(() => {
@@ -389,8 +253,8 @@ describe('ProxyForm', () => {
render(<ProxyForm />);
await user.click(screen.getAllByRole('switch')[0]);
- await user.type(screen.getByRole('textbox', { name: 'proxy.server' }), '127.0.0.1');
- await user.type(screen.getByRole('textbox', { name: 'proxy.port' }), '7890');
+ await user.type(screen.getByPlaceholderText('127.0.0.1'), '127.0.0.1');
+ await user.type(screen.getByPlaceholderText('7890'), '7890');
await user.click(screen.getByRole('button', { name: 'proxy.testButton' }));
await waitFor(() => {
diff --git a/src/features/Settings/skill/features/SkillDetail/index.test.tsx b/src/features/Settings/skill/features/SkillDetail/index.test.tsx
index 7603d080e59..d91a9552e1d 100644
--- a/src/features/Settings/skill/features/SkillDetail/index.test.tsx
+++ b/src/features/Settings/skill/features/SkillDetail/index.test.tsx
@@ -77,49 +77,11 @@ vi.mock('@lobechat/const', () => ({
: undefined,
}));
-vi.mock('@lobehub/ui', () => ({
- Avatar: () => <div data-testid="avatar" />,
- Markdown: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Skeleton: () => <div data-testid="skeleton" />,
-}));
-
-// Stub the base-ui Button to a native button — it needs a MotionProvider the
-// app sets up globally but the unit env doesn't.
-vi.mock('@lobehub/ui/base-ui', () => ({
- Button: ({
- children,
- disabled,
- onClick,
- }: {
- children?: ReactNode;
- disabled?: boolean;
- onClick?: () => void;
- }) => (
- <button disabled={disabled} type="button" onClick={onClick}>
- {children}
- </button>
- ),
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
confirmModal: mocks.confirmModal,
}));
-vi.mock('antd-style', () => ({
- createStaticStyles: (
- creator: (tokens: {
- css: () => string;
- cssVar: Record<string, string>;
- }) => Record<string, string>,
- ) =>
- creator({
- css: () => '',
- cssVar: {
- colorBorderSecondary: 'colorBorderSecondary',
- colorText: 'colorText',
- colorTextSecondary: 'colorTextSecondary',
- colorTextTertiary: 'colorTextTertiary',
- },
- }),
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, options?: { defaultValue?: string; name?: string } | string) => {
diff --git a/src/features/Settings/stats/features/usage/UsageCards/ActiveModels/index.test.tsx b/src/features/Settings/stats/features/usage/UsageCards/ActiveModels/index.test.tsx
index bdeebb920d9..eeef53b8ff0 100644
--- a/src/features/Settings/stats/features/usage/UsageCards/ActiveModels/index.test.tsx
+++ b/src/features/Settings/stats/features/usage/UsageCards/ActiveModels/index.test.tsx
@@ -10,28 +10,16 @@ import type { UsageLog } from '@/types/usage/usageRecord';
import { GroupBy } from '../../../../types';
import ActiveModels from './index';
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('@lobehub/icons', () => ({
ModelIcon: ({ model }: { model: string }) => <span>{model}</span>,
ProviderIcon: ({ provider }: { provider: string }) => <span>{provider}</span>,
}));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Modal: () => null,
-}));
-
vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
const actual = (await importOriginal()) as Record<string, unknown>;
return {
...actual,
- ActionIcon: () => <button type="button" />,
Avatar: ({ avatar, title }: { avatar?: string | null; title?: string }) => (
<span aria-label={title} data-testid="active-user-avatar">
{avatar}
diff --git a/src/features/Settings/stats/features/usage/UsageTable.test.tsx b/src/features/Settings/stats/features/usage/UsageTable.test.tsx
index a8a197c53d2..542d12f98cf 100644
--- a/src/features/Settings/stats/features/usage/UsageTable.test.tsx
+++ b/src/features/Settings/stats/features/usage/UsageTable.test.tsx
@@ -9,10 +9,6 @@ import { describe, expect, it, vi } from 'vitest';
import UsageTable from './UsageTable';
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@lobehub/icons', () => ({
ProviderIcon: ({ provider }: { provider: string }) => <span>{provider}</span>,
}));
diff --git a/src/features/Settings/storage/features/Advanced.test.tsx b/src/features/Settings/storage/features/Advanced.test.tsx
index 3409b2c07ca..651922086d7 100644
--- a/src/features/Settings/storage/features/Advanced.test.tsx
+++ b/src/features/Settings/storage/features/Advanced.test.tsx
@@ -19,61 +19,6 @@ vi.hoisted(() => {
});
});
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Button: ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
- <button onClick={onClick}>{children}</button>
- ),
- Form: ({
- items,
- }: {
- items: {
- children: { children?: ReactNode; desc?: string; label: string }[];
- title: string;
- }[];
- }) => (
- <div>
- {items.map((group) => (
- <section key={group.title}>
- <h2>{group.title}</h2>
- {group.children.map((item) => (
- <div key={item.label}>
- <span>{item.label}</span>
- {item.desc && <span>{item.desc}</span>}
- {item.children}
- </div>
- ))}
- </section>
- ))}
- </div>
- ),
- Icon: () => null,
- ShikiLobeTheme: {},
-}));
-
-vi.mock('antd', () => ({
- App: {
- useApp: () => ({
- message: { success: vi.fn() },
- modal: { confirm: vi.fn() },
- }),
- },
- Switch: ({ checked, onChange }: { checked?: boolean; onChange?: (checked: boolean) => void }) => (
- <button
- aria-checked={checked}
- role="switch"
- onClick={() => {
- onChange?.(!checked);
- }}
- />
- ),
-}));
-
vi.mock('@/business/client/features/AccountDeletion', () => ({
default: () => <div />,
}));
diff --git a/src/features/SuggestQuestions/index.test.tsx b/src/features/SuggestQuestions/index.test.tsx
index 89e1df491b8..26aca2ed000 100644
--- a/src/features/SuggestQuestions/index.test.tsx
+++ b/src/features/SuggestQuestions/index.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import SuggestQuestions from './index';
@@ -11,10 +10,6 @@ const permissionMock = vi.hoisted(() => ({
allowed: true,
}));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}));
-
vi.mock('@/hooks/usePermission', () => ({
usePermission: () => ({
allowed: permissionMock.allowed,
diff --git a/src/features/TopicCreatorAvatar/index.test.tsx b/src/features/TopicCreatorAvatar/index.test.tsx
index da8e9b788b7..a48037c3fe1 100644
--- a/src/features/TopicCreatorAvatar/index.test.tsx
+++ b/src/features/TopicCreatorAvatar/index.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { render } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { describe, expect, it, vi } from 'vitest';
import TopicCreatorAvatar from './index';
@@ -13,10 +12,6 @@ vi.mock('@/business/client/hooks/useAuthorInfo', () => ({
useAuthorInfo: useAuthorInfoMock,
}));
-vi.mock('@lobehub/ui', () => ({
- Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
-}));
-
// The identity-preserving wrapper owns the initials/background fallback; this
// component's contract is only what it hands over.
vi.mock('@/components/Avatar', () => ({
diff --git a/src/features/User/__tests__/PanelContent.test.tsx b/src/features/User/__tests__/PanelContent.test.tsx
index 3b41ca2ae0e..1284d3bf8b3 100644
--- a/src/features/User/__tests__/PanelContent.test.tsx
+++ b/src/features/User/__tests__/PanelContent.test.tsx
@@ -7,8 +7,6 @@ import { useUserStore } from '@/store/user';
import PanelContent from '../UserPanel/PanelContent';
// Mock dependencies
-vi.mock('zustand/traditional');
-
vi.mock('next/navigation', () => ({
useRouter: vi.fn(() => ({
push: vi.fn(),
diff --git a/src/features/User/__tests__/UserAvatar.test.tsx b/src/features/User/__tests__/UserAvatar.test.tsx
index afd6d5af12c..80b40094024 100644
--- a/src/features/User/__tests__/UserAvatar.test.tsx
+++ b/src/features/User/__tests__/UserAvatar.test.tsx
@@ -1,14 +1,12 @@
import { BRANDING_NAME } from '@lobechat/business-const';
import { act, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
import { DEFAULT_USER_AVATAR_URL } from '@/const/meta';
import { useUserStore } from '@/store/user';
import UserAvatar from '../UserAvatar';
-vi.mock('zustand/traditional');
-
describe('UserAvatar', () => {
it('should show the username and avatar are displayed when the user is logged in', async () => {
const mockAvatar = 'https://example.com/avatar.png';
diff --git a/src/features/VisibilityConfirmContent/index.test.tsx b/src/features/VisibilityConfirmContent/index.test.tsx
index 5d1b3ba7c33..2a30b59c925 100644
--- a/src/features/VisibilityConfirmContent/index.test.tsx
+++ b/src/features/VisibilityConfirmContent/index.test.tsx
@@ -2,20 +2,10 @@
* @vitest-environment happy-dom
*/
import { render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
import VisibilityConfirmContent from './index';
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Icon: ({ size }: { icon: unknown; size?: number }) => (
- <span data-icon-size={size} data-testid="icon" />
- ),
-}));
-
describe('VisibilityConfirmContent', () => {
it('renders 3 makePrivate items in escalation order with an irreversible suffix on the last', () => {
render(<VisibilityConfirmContent variant="makePrivate" />);
diff --git a/src/features/WorkspaceSetting/Layout.test.tsx b/src/features/WorkspaceSetting/Layout.test.tsx
index 5e805dab52e..dd76612f3f6 100644
--- a/src/features/WorkspaceSetting/Layout.test.tsx
+++ b/src/features/WorkspaceSetting/Layout.test.tsx
@@ -10,11 +10,6 @@ vi.mock('@/features/NavHeader', () => ({
React.createElement('header', undefined, children),
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- Text: ({ children }: { children?: React.ReactNode }) =>
- React.createElement(React.Fragment, undefined, children),
-}));
-
vi.mock('./Container', () => ({
default: ({ children }: { children?: React.ReactNode }) =>
React.createElement('main', undefined, children),
@@ -72,7 +67,9 @@ describe('WorkspaceSettingsContentLayout', () => {
])('renders the compact header for the %s tab', (tab, title) => {
const html = renderLayout(tab);
- expect(html).toContain(`<header>${title}</header>`);
+ expect(html).toMatch(
+ new RegExp(`<header>(?:(?!</header>).)*>${title}<(?:(?!<header>).)*</header>`),
+ );
expect(html).toContain('<main><div>Page content</div></main>');
});
diff --git a/src/features/WorkspaceSetting/hooks/useCategory.test.tsx b/src/features/WorkspaceSetting/hooks/useCategory.test.tsx
index 4cf9a640f4b..3e1fc966501 100644
--- a/src/features/WorkspaceSetting/hooks/useCategory.test.tsx
+++ b/src/features/WorkspaceSetting/hooks/useCategory.test.tsx
@@ -23,12 +23,6 @@ const mocks = vi.hoisted(() => ({
canViewBilling: true,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
const permissionFlags: Record<string, () => boolean> = {
create_content: () => mocks.canCreateContent,
view_billing: () => mocks.canViewBilling,
diff --git a/src/hooks/useNavLayout.test.tsx b/src/hooks/useNavLayout.test.tsx
index 39e4971b676..897752cf642 100644
--- a/src/hooks/useNavLayout.test.tsx
+++ b/src/hooks/useNavLayout.test.tsx
@@ -10,10 +10,6 @@ const mocks = vi.hoisted(() => ({
showMarket: true,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/config/routes', () => ({
getRouteById: (id: string) => ({
icon: () => id,
diff --git a/src/hooks/useOperationState.test.ts b/src/hooks/useOperationState.test.ts
index 15e00cb56fe..7c414677fe0 100644
--- a/src/hooks/useOperationState.test.ts
+++ b/src/hooks/useOperationState.test.ts
@@ -7,8 +7,6 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { useOperationState } from './useOperationState';
-vi.mock('zustand/traditional');
-
describe('useOperationState', () => {
const TEST_CONTEXT = {
agentId: 'test-agent-id',
diff --git a/src/hooks/useTopicSharePermission.test.ts b/src/hooks/useTopicSharePermission.test.ts
index 41da3807d90..86d8058d7b1 100644
--- a/src/hooks/useTopicSharePermission.test.ts
+++ b/src/hooks/useTopicSharePermission.test.ts
@@ -16,10 +16,6 @@ vi.mock('@/hooks/usePermission', () => ({
usePermission: (action: string) => mocks.permissions[action],
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/store/agent', () => ({
useAgentStore: (selector: (state: unknown) => unknown) => selector({ agentMap: mocks.agentMap }),
}));
diff --git a/src/hooks/useUserAvatar.test.ts b/src/hooks/useUserAvatar.test.ts
index 852f58058db..1796668f856 100644
--- a/src/hooks/useUserAvatar.test.ts
+++ b/src/hooks/useUserAvatar.test.ts
@@ -7,8 +7,6 @@ import { useUserStore } from '@/store/user';
import { useUserAvatar } from './useUserAvatar';
-vi.mock('zustand/traditional');
-
const mockConstEnv = vi.hoisted(() => ({ isDesktop: false }));
vi.mock('@lobechat/const', async (importOriginal) => {
diff --git a/src/initialize.test.ts b/src/initialize.test.ts
index b4259c4c572..19cefb24e06 100644
--- a/src/initialize.test.ts
+++ b/src/initialize.test.ts
@@ -2,7 +2,10 @@ import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
const { toastError } = vi.hoisted(() => ({ toastError: vi.fn() }));
-vi.mock('@lobehub/ui/base-ui', () => ({ toast: { error: toastError } }));
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ toast: { error: toastError },
+}));
const reload = vi.fn();
diff --git a/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.test.tsx b/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.test.tsx
index beec762c3a1..b1b7385f9f6 100644
--- a/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.test.tsx
+++ b/src/layout/AuthProvider/MarketAuth/ClaimResourcesModal.test.tsx
@@ -2,14 +2,11 @@
* @vitest-environment happy-dom
*/
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import type { HTMLAttributes, ReactNode } from 'react';
+import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import ClaimResourcesModal from './ClaimResourcesModal';
-const messageErrorMock = vi.hoisted(() => vi.fn());
-const messageSuccessMock = vi.hoisted(() => vi.fn());
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, options?: Record<string, string | number>) =>
@@ -42,45 +39,6 @@ vi.mock('@/components/ImperativeModal', () => ({
) : null,
}));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children, ...props }: HTMLAttributes<HTMLDivElement>) => (
- <div {...props}>{children}</div>
- ),
- Text: ({ children, ...props }: HTMLAttributes<HTMLSpanElement>) => (
- <span {...props}>{children}</span>
- ),
-}));
-
-vi.mock('antd', () => {
- const ListItem = ({ children, onClick }: { children: ReactNode; onClick?: () => void }) => (
- <div role="listitem" onClick={onClick}>
- {children}
- </div>
- );
-
- const List = ({
- dataSource,
- renderItem,
- }: {
- dataSource: any[];
- renderItem: (item: any) => ReactNode;
- }) => <div>{dataSource.map((item) => renderItem(item))}</div>;
-
- List.Item = ListItem;
-
- return {
- App: {
- useApp: () => ({
- message: {
- error: messageErrorMock,
- success: messageSuccessMock,
- },
- }),
- },
- List,
- };
-});
-
vi.mock('@/libs/trpc/client', () => ({
lambdaClient: {
market: {
diff --git a/src/layout/SPAGlobalProvider/index.test.tsx b/src/layout/SPAGlobalProvider/index.test.tsx
index 1b2b8a84a2e..5d7045c74f6 100644
--- a/src/layout/SPAGlobalProvider/index.test.tsx
+++ b/src/layout/SPAGlobalProvider/index.test.tsx
@@ -19,47 +19,27 @@ const { cacheGateReleased, canAccessDevDock, devDockRenderError } = vi.hoisted((
devDockRenderError: { current: null as Error | null },
}));
-vi.mock('@lobehub/ui', async () => {
+vi.mock('@lobehub/ui', async (importOriginal) => {
const React = await import('react');
- const Passthrough = ({ children }: { children?: ReactNode }) =>
- React.createElement(React.Fragment, null, children);
return {
+ ...(await importOriginal<object>()),
ContextMenuHost: () => React.createElement('div', { 'data-testid': 'context-menu-host' }),
ModalHost: () => React.createElement('div', { 'data-testid': 'legacy-modal-host' }),
- TooltipGroup: Passthrough,
setContextMenuInterceptor: vi.fn(),
};
});
-vi.mock('@lobehub/ui/base-ui', async () => {
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
const React = await import('react');
return {
+ ...(await importOriginal<object>()),
ModalHost: () => React.createElement('div', { 'data-testid': 'base-modal-host' }),
ToastHost: () => React.createElement('div', { 'data-testid': 'toast-host' }),
};
});
-vi.mock('antd-style', async () => {
- const React = await import('react');
-
- return {
- StyleProvider: ({ children }: { children?: ReactNode }) =>
- React.createElement(React.Fragment, null, children),
- };
-});
-
-vi.mock('motion/react', async () => {
- const React = await import('react');
-
- return {
- LazyMotion: ({ children }: { children?: ReactNode }) =>
- React.createElement(React.Fragment, null, children),
- domMax: {},
- };
-});
-
vi.mock('@/components/Analytics/LobeAnalyticsProviderWrapper', async () => {
const React = await import('react');
@@ -196,7 +176,7 @@ describe('SPAGlobalProvider', () => {
const loadedModule = await import('./index');
SPAGlobalProvider = loadedModule.default;
DevDockLayout = loadedModule.DevDockLayout;
- });
+ }, 30_000);
beforeEach(() => {
cacheGateReleased.current = true;
diff --git a/src/routes/(main)/(create)/features/CreateGenerationPage.test.tsx b/src/routes/(main)/(create)/features/CreateGenerationPage.test.tsx
index 56bfc37ddcd..ca60ccabb90 100644
--- a/src/routes/(main)/(create)/features/CreateGenerationPage.test.tsx
+++ b/src/routes/(main)/(create)/features/CreateGenerationPage.test.tsx
@@ -5,17 +5,6 @@ import { describe, expect, it, vi } from 'vitest';
import CreateGenerationPage from './CreateGenerationPage';
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
-}));
-
-vi.mock('motion/react', () => ({
- AnimatePresence: ({ children }: { children?: ReactNode }) => <>{children}</>,
- m: {
- div: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- },
-}));
-
vi.mock('@/features/NavHeader', () => ({
default: () => <div data-testid="nav-header" />,
}));
diff --git a/src/routes/(main)/(create)/features/GenerationInput/GenerationMediaModeSegment.test.tsx b/src/routes/(main)/(create)/features/GenerationInput/GenerationMediaModeSegment.test.tsx
index 3aca90c4a18..fed65f2b462 100644
--- a/src/routes/(main)/(create)/features/GenerationInput/GenerationMediaModeSegment.test.tsx
+++ b/src/routes/(main)/(create)/features/GenerationInput/GenerationMediaModeSegment.test.tsx
@@ -20,11 +20,6 @@ const componentMocks = vi.hoisted(() => ({
segmented: undefined as SegmentedCapture | undefined,
}));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children: ReactNode }) => <div>{children}</div>,
- Icon: () => <span data-testid="mode-icon" />,
-}));
-
vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
...((await importOriginal()) as Record<string, unknown>),
ActionIcon: ({ title }: { title?: ReactNode }) => (
@@ -70,10 +65,6 @@ vi.mock('@/features/ChatInput/ActionBar/components/ActionPopover', () => ({
),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/store/serverConfig', () => ({
useServerConfigStore: <T,>(selector: (state: { isMobile: boolean }) => T) =>
selector({ isMobile: false }),
@@ -83,9 +74,10 @@ describe('GenerationMediaModeSegment', () => {
it('uses an icon-only toggle group in the composer toolbar', () => {
render(<GenerationMediaModeSegment mode="image" />);
- expect(screen.getByTestId('mode-toggle-group')).toBeInTheDocument();
+ const toggleGroup = screen.getByTestId('mode-toggle-group');
+ expect(toggleGroup).toBeInTheDocument();
expect(screen.queryByTestId('mode-select')).not.toBeInTheDocument();
- expect(screen.getAllByTestId('mode-icon')).toHaveLength(2);
+ expect(toggleGroup.querySelectorAll('svg')).toHaveLength(2);
expect(screen.queryByText('tab.image')).not.toBeInTheDocument();
expect(screen.queryByText('tab.video')).not.toBeInTheDocument();
expect(componentMocks.segmented?.options?.map((option) => option.label)).toEqual([
diff --git a/src/routes/(main)/(create)/image/_layout/Sidebar/Content.test.tsx b/src/routes/(main)/(create)/image/_layout/Sidebar/Content.test.tsx
index cf8ad94fdf8..ea900231a38 100644
--- a/src/routes/(main)/(create)/image/_layout/Sidebar/Content.test.tsx
+++ b/src/routes/(main)/(create)/image/_layout/Sidebar/Content.test.tsx
@@ -10,41 +10,6 @@ const mocks = vi.hoisted(() => ({
updateSystemStatus: vi.fn(),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Accordion: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- AccordionItem: ({
- action,
- children,
- title,
- }: {
- action?: ReactNode;
- children?: ReactNode;
- title?: ReactNode;
- }) => (
- <section>
- <header>
- {title}
- {action}
- </header>
- {children}
- </section>
- ),
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Icon: () => <span />,
-}));
-
-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
- ...((await importOriginal()) as Record<string, unknown>),
- Tabs: () => <div />,
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
-}));
-
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => mocks.activeWorkspaceId,
}));
diff --git a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/ErrorState.test.tsx b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/ErrorState.test.tsx
index 34705a68492..dcebc922194 100644
--- a/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/ErrorState.test.tsx
+++ b/src/routes/(main)/(create)/image/features/GenerationFeed/GenerationItem/ErrorState.test.tsx
@@ -6,19 +6,6 @@ import { type Generation, type GenerationBatch } from '@/types/generation';
import { ErrorState } from './ErrorState';
-vi.mock('@lobehub/ui', async () => {
- const React = await import('react');
-
- return {
- ActionIconGroup: () => React.createElement('div', { 'data-testid': 'action-buttons' }),
- Block: ({ children, onClick, style }: any) =>
- React.createElement('div', { onClick, style }, children),
- Center: ({ children }: any) => React.createElement('div', null, children),
- Icon: () => React.createElement('span', { 'data-testid': 'icon' }),
- Text: ({ children }: any) => React.createElement('span', null, children),
- };
-});
-
vi.mock('./styles', () => ({
styles: {
generationActionButton: 'generation-actions',
diff --git a/src/routes/(main)/agent/_layout/index.test.tsx b/src/routes/(main)/agent/_layout/index.test.tsx
index 7b42c4a0dcc..710fb95bd64 100644
--- a/src/routes/(main)/agent/_layout/index.test.tsx
+++ b/src/routes/(main)/agent/_layout/index.test.tsx
@@ -2,18 +2,10 @@
* @vitest-environment happy-dom
*/
import { render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { describe, expect, it, vi } from 'vitest';
import Layout from './index';
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
- <div {...props}>{children}</div>
- ),
- ShikiLobeTheme: {},
-}));
-
vi.mock('react-router', async () => {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
const actual = (await vi.importActual('react-router')) as typeof import('react-router');
diff --git a/src/routes/(main)/agent/channel/detail/permission.test.tsx b/src/routes/(main)/agent/channel/detail/permission.test.tsx
index a86e7f9e659..e2cd559c188 100644
--- a/src/routes/(main)/agent/channel/detail/permission.test.tsx
+++ b/src/routes/(main)/agent/channel/detail/permission.test.tsx
@@ -52,10 +52,6 @@ vi.mock('antd', async (importOriginal) => {
};
});
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => mocks.activeWorkspaceId,
}));
@@ -116,84 +112,6 @@ vi.mock('@/hooks/useAppOrigin', () => ({
useAppOrigin: () => 'https://example.test',
}));
-vi.mock('@lobehub/ui', () => ({
- ActionIcon: ({
- disabled,
- onClick,
- title,
- }: {
- disabled?: boolean;
- onClick?: () => void;
- title?: string;
- }) => (
- <button aria-label={title} disabled={disabled} onClick={onClick}>
- {title}
- </button>
- ),
- Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Flexbox: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
- <div {...props}>{children}</div>
- ),
- Form: ({
- children,
- form,
- onValuesChange,
- }: {
- children?: ReactNode;
- form?: ReturnType<typeof Form.useForm>[0];
- onValuesChange?: (changedValues: unknown, values: unknown) => void;
- }) => (
- <Form form={form} onValuesChange={onValuesChange}>
- {children}
- </Form>
- ),
- FormGroup: ({
- active,
- children,
- extra,
- onCollapse,
- title,
- }: {
- active?: boolean;
- children?: ReactNode;
- extra?: ReactNode;
- onCollapse?: (active: boolean) => void;
- title?: ReactNode;
- }) => (
- <section>
- <div
- className="ant-collapse-header"
- data-testid="settings-collapse-header"
- onClick={() => onCollapse?.(!active)}
- >
- <span className="ant-collapse-title">{title}</span>
- <div className="ant-collapse-extra">{extra}</div>
- </div>
- {active && children}
- </section>
- ),
- FormItem: ({
- children,
- label,
- name,
- rules,
- valuePropName,
- }: {
- children?: ReactNode;
- label?: ReactNode;
- name?: string | string[];
- rules?: unknown[];
- valuePropName?: string;
- }) => (
- <Form.Item label={label} name={name} rules={rules as never} valuePropName={valuePropName}>
- {children}
- </Form.Item>
- ),
- Icon: () => null,
- Tag: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
-}));
-
vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
...((await importOriginal()) as Record<string, unknown>),
ActionIcon: ({
@@ -225,19 +143,6 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
<div data-testid="channel-paid-alert-description">{description}</div>
</div>
),
- Button: ({
- children,
- disabled,
- icon,
- loading,
- onClick,
- ...rest
- }: React.ButtonHTMLAttributes<HTMLButtonElement> & { icon?: ReactNode; loading?: boolean }) => (
- <button disabled={disabled || loading} onClick={onClick} {...rest}>
- {icon}
- {children}
- </button>
- ),
DropdownMenu: ({
children,
items,
@@ -252,22 +157,6 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
))}
</div>
),
- Switch: ({
- checked,
- disabled,
- onChange,
- }: {
- checked?: boolean;
- disabled?: boolean;
- onChange?: (next: boolean) => void;
- }) => (
- <button
- aria-checked={checked}
- disabled={disabled}
- role="switch"
- onClick={() => onChange?.(!checked)}
- />
- ),
}));
vi.mock('@/components/FormInput', () => ({
@@ -397,14 +286,20 @@ describe('Agent channel permission gates', () => {
it('toggles advanced settings from the full header row', () => {
render(<BodyHarness />);
- const header = screen.getByTestId('settings-collapse-header');
+ const header = document.querySelector('.ant-collapse-header') as HTMLElement;
+ expect(header).not.toBeNull();
expect(screen.getByRole('spinbutton', { name: 'channel.charLimit' })).toBeInTheDocument();
+ const panel = () =>
+ screen
+ .getByRole('spinbutton', { hidden: true, name: 'channel.charLimit' })
+ .closest('.ant-collapse-panel');
+
fireEvent.click(header);
- expect(screen.queryByRole('spinbutton', { name: 'channel.charLimit' })).not.toBeInTheDocument();
+ expect(panel()).toHaveClass('ant-collapse-panel-inactive');
fireEvent.click(header);
- expect(screen.getByRole('spinbutton', { name: 'channel.charLimit' })).toBeInTheDocument();
+ expect(panel()).not.toHaveClass('ant-collapse-panel-inactive');
});
it('disables mutating channel actions when editing is denied', () => {
@@ -435,7 +330,7 @@ describe('Agent channel permission gates', () => {
await waitFor(() =>
expect(screen.getByRole('textbox', { name: 'channel.applicationId' })).toHaveValue('app-id'),
);
- });
+ }, 15_000);
it('disables the channel enable switch and status refresh when editing is denied', () => {
render(
diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.test.tsx
index cb10612c7b5..c89047ded17 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/index.test.tsx
@@ -1,38 +1,8 @@
-import { render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
+import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import HeaderActions from './index';
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ title, onClick }: { title?: string; onClick?: () => void }) => (
- <button
- aria-label={title}
- data-testid={title ? undefined : 'overflow-menu-button'}
- onClick={onClick}
- />
- ),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- DropdownMenu: ({ children, header }: { children?: ReactNode; header?: ReactNode }) => (
- <div>
- {header}
- {children}
- </div>
- ),
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ title, onClick }: { title?: string; onClick?: () => void }) => (
- <button
- aria-label={title}
- data-testid={title ? undefined : 'overflow-menu-button'}
- onClick={onClick}
- />
- ),
-}));
-
vi.mock('./useMenu', () => ({
useMenu: () => ({
menuHeader: <div data-testid={'topic-info-header'} />,
@@ -44,12 +14,14 @@ describe('Conversation header actions', () => {
it('renders the overflow actions button', () => {
render(<HeaderActions />);
- expect(screen.getByTestId('overflow-menu-button')).toBeInTheDocument();
+ expect(screen.getByRole('button')).toBeInTheDocument();
});
- it('passes the topic info header to the dropdown', () => {
+ it('passes the topic info header to the dropdown', async () => {
render(<HeaderActions />);
- expect(screen.getByTestId('topic-info-header')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button'));
+
+ expect(await screen.findByTestId('topic-info-header')).toBeInTheDocument();
});
});
diff --git a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx
index f4ec0cd1a20..b9b03c70c8f 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/HeaderActions/useMenu.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { act, render, renderHook, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { describe, expect, it, vi } from 'vitest';
import { useMenu } from './useMenu';
@@ -33,21 +32,20 @@ vi.mock('@/features/Conversation/useAgentContext', () => ({
useAgentContext: () => ({ agentId: 'agent-1', topicId: 'topic-1' }),
}));
-vi.mock('@lobehub/ui', () => ({
- Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Icon: () => null,
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
-}));
-
-vi.mock('antd', () => ({
- App: {
- useApp: () => ({
- message: { success: messageSuccessMock },
- modal: { confirm: modalConfirmMock },
- }),
- },
-}));
+vi.mock('antd', async (importOriginal) => {
+ const actual = await importOriginal<{ App: Record<string, unknown> } & Record<string, unknown>>();
+
+ return {
+ ...actual,
+ App: {
+ ...actual.App,
+ useApp: () => ({
+ message: { success: messageSuccessMock },
+ modal: { confirm: modalConfirmMock },
+ }),
+ },
+ };
+});
vi.mock('react-i18next', () => ({
useTranslation: () => ({
diff --git a/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.test.tsx
index 092a29df9e6..b7b352b7a5d 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/ShareButton/index.test.tsx
@@ -1,8 +1,9 @@
/**
* @vitest-environment happy-dom
*/
+import type * as BaseUI from '@lobehub/ui/base-ui';
import { render } from '@testing-library/react';
-import type { ComponentType, ReactNode } from 'react';
+import type { ComponentProps, ComponentType, ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import ShareButton from './index';
@@ -16,22 +17,18 @@ const mocks = vi.hoisted(() => ({
},
}));
-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
- ...((await importOriginal()) as Record<string, unknown>),
- ActionIcon: ({
- disabled,
- onClick,
- title,
- }: {
- disabled?: boolean;
- onClick?: () => void;
- title?: string;
- }) => (
- <button data-testid="share-button" disabled={disabled} title={title} onClick={onClick}>
- {title}
- </button>
- ),
-}));
+const actionIconPropsSpy = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
+ const actual = await importOriginal<typeof BaseUI>();
+ return {
+ ...actual,
+ ActionIcon: (props: ComponentProps<typeof actual.ActionIcon>) => {
+ actionIconPropsSpy(props);
+ return <actual.ActionIcon {...props} />;
+ },
+ };
+});
vi.mock('next/dynamic', () => ({
default: () =>
@@ -40,12 +37,6 @@ vi.mock('next/dynamic', () => ({
},
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('@/components/withSuspense', () => ({
withSuspense: (Component: ComponentType) => Component,
}));
@@ -82,15 +73,21 @@ describe('Conversation ShareButton', () => {
mocks.activeTopicId = 'topic-1';
mocks.enableBusinessFeatures = true;
mocks.permission.allowed = true;
+ actionIconPropsSpy.mockClear();
});
it('does not open share popover for workspace viewers', () => {
mocks.permission.allowed = false;
- const { queryByTestId, getByTestId } = render(<ShareButton />);
+ const { queryByTestId } = render(<ShareButton />);
- expect(getByTestId('share-button')).toBeDisabled();
- expect(getByTestId('share-button')).toHaveAttribute('title', 'requires member');
+ expect(actionIconPropsSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ disabled: true,
+ onClick: undefined,
+ title: 'requires member',
+ }),
+ );
expect(queryByTestId('share-popover')).toBeNull();
});
});
diff --git a/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx b/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx
index aa8d38a2d95..d292ca2e081 100644
--- a/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/Header/TerminalPanelToggle/index.test.tsx
@@ -1,4 +1,6 @@
+import type * as BaseUI from '@lobehub/ui/base-ui';
import { fireEvent, render, screen } from '@testing-library/react';
+import type { ComponentProps } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import TerminalPanelToggle from './index';
@@ -8,21 +10,18 @@ const mocks = vi.hoisted(() => ({
toggleTerminalPanel: vi.fn(),
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ active, onClick }: { active?: boolean; onClick?: () => void }) => (
- <button data-active={String(active)} data-testid="terminal-panel-toggle" onClick={onClick} />
- ),
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ active, onClick }: { active?: boolean; onClick?: () => void }) => (
- <button data-active={String(active)} data-testid="terminal-panel-toggle" onClick={onClick} />
- ),
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
+const actionIconPropsSpy = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
+ const actual = await importOriginal<typeof BaseUI>();
+ return {
+ ...actual,
+ ActionIcon: (props: ComponentProps<typeof actual.ActionIcon>) => {
+ actionIconPropsSpy(props);
+ return <actual.ActionIcon {...props} />;
+ },
+ };
+});
vi.mock('@/const/version', () => ({ isDesktop: true }));
@@ -60,20 +59,22 @@ describe('TerminalPanelToggle', () => {
beforeEach(() => {
mocks.showTerminalPanel = false;
mocks.toggleTerminalPanel.mockReset();
+ actionIconPropsSpy.mockClear();
});
it('toggles the panel and reflects its active state', () => {
const { rerender } = render(<TerminalPanelToggle />);
- expect(screen.getByTestId('terminal-panel-toggle')).toHaveAttribute('data-active', 'false');
+ expect(actionIconPropsSpy).toHaveBeenCalledWith(expect.objectContaining({ active: false }));
- fireEvent.click(screen.getByTestId('terminal-panel-toggle'));
+ fireEvent.click(screen.getByRole('button'));
expect(mocks.toggleTerminalPanel).toHaveBeenCalledTimes(1);
expect(mocks.toggleTerminalPanel).toHaveBeenCalledWith();
mocks.showTerminalPanel = true;
+ actionIconPropsSpy.mockClear();
rerender(<TerminalPanelToggle key="open" />);
- expect(screen.getByTestId('terminal-panel-toggle')).toHaveAttribute('data-active', 'true');
+ expect(actionIconPropsSpy).toHaveBeenCalledWith(expect.objectContaining({ active: true }));
});
});
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx
index 690661e131a..b56c5f32888 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx
@@ -127,26 +127,11 @@ vi.mock('react-i18next', () => ({
}),
}));
-vi.mock('antd-style', async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
- const mockCssVar = new Proxy({}, { get: (_target, prop) => `var(--${String(prop)})` });
- return {
- ...actual,
- createStaticStyles: (
- create: (utils: {
- css: (...args: unknown[]) => string;
- cssVar: Record<string, string>;
- }) => Record<string, string>,
- ) => create({ css: () => 'cls', cssVar: mockCssVar }),
- cssVar: mockCssVar,
- cx: (...args: unknown[]) => args.filter(Boolean).join(' '),
- };
-});
-
-vi.mock('@lobehub/ui', async () => {
+vi.mock('@lobehub/ui', async (importOriginal) => {
const { useState } = await import('react');
return {
+ ...(await importOriginal<object>()),
ActionIcon: ({
disabled,
onClick,
@@ -222,7 +207,8 @@ vi.mock('@lobehub/ui', async () => {
};
});
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...((await importOriginal()) as Record<string, unknown>),
ActionIcon: ({
onClick,
title,
@@ -240,25 +226,6 @@ vi.mock('@lobehub/ui/base-ui', () => ({
onClick={onClick}
/>
),
- RadioGroup: () => null,
- Switch: () => null,
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
- createModal: vi.fn(),
- Button: ({
- children,
- disabled,
- loading,
- onClick,
- }: {
- children?: ReactNode;
- disabled?: boolean;
- loading?: boolean;
- onClick?: () => void;
- }) => (
- <button disabled={disabled || loading} type="button" onClick={onClick}>
- {children}
- </button>
- ),
confirmModal: confirmModalMock,
toast: {
error: toastErrorMock,
diff --git a/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.test.tsx b/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.test.tsx
index 70ba2f657a3..c9c0770def5 100644
--- a/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.test.tsx
+++ b/src/routes/(main)/agent/features/Conversation/MainChatInput/useSendMenuItems.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { act, renderHook } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useSendMenuItems as useGroupSendMenuItems } from '@/routes/(main)/group/features/Conversation/MainChatInput/useSendMenuItems';
@@ -19,12 +18,6 @@ const mocks = vi.hoisted(() => ({
updatePreference: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children?: ReactNode }) => children,
- Hotkey: () => null,
- Icon: () => null,
-}));
-
vi.mock('react-i18next', () => ({
Trans: () => null,
useTranslation: () => ({ t: (key: string) => key }),
diff --git a/src/routes/(main)/agent/index.desktop.test.tsx b/src/routes/(main)/agent/index.desktop.test.tsx
index 841520ecaad..437c774a43c 100644
--- a/src/routes/(main)/agent/index.desktop.test.tsx
+++ b/src/routes/(main)/agent/index.desktop.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { act, render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -25,23 +24,6 @@ vi.hoisted(() => {
});
});
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({
- children,
- horizontal,
- ...props
- }: {
- children?: ReactNode;
- horizontal?: boolean;
- [key: string]: unknown;
- }) => (
- <div data-horizontal={horizontal ? 'true' : undefined} {...props}>
- {children}
- </div>
- ),
- ShikiLobeTheme: {},
-}));
-
vi.mock('@/features/TopicPopupGuard', () => ({
default: () => <div data-testid="topic-popup-guard" />,
}));
diff --git a/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx b/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx
index c1b1231c4a6..253f696191d 100644
--- a/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx
+++ b/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx
@@ -46,10 +46,6 @@ vi.mock('@/features/AgentSetting', () => ({
),
}));
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/store/agent', () => {
const useAgentStore = (selector: (state: typeof mocks.agentState) => unknown) =>
selector(mocks.agentState);
@@ -76,12 +72,6 @@ vi.mock('@/store/serverConfig', () => ({
selector(mocks.serverState),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
describe('AgentSettings Content', () => {
beforeEach(() => {
mocks.agentState.isInbox = true;
diff --git a/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsx b/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsx
index 9077d415260..5153585bbd0 100644
--- a/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsx
+++ b/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsx
@@ -128,18 +128,8 @@ vi.mock('@/components/InfoTooltip', () => ({
),
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({
- 'aria-label': ariaLabel,
- 'aria-pressed': ariaPressed,
- onClick,
- }: {
- 'aria-label'?: string;
- 'aria-pressed'?: boolean;
- 'onClick'?: (e: any) => void;
- }) => (
- <button aria-label={ariaLabel} aria-pressed={ariaPressed} type="button" onClick={onClick} />
- ),
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
toast: {
error: (...args: unknown[]) => messageError(...args),
},
@@ -190,10 +180,6 @@ vi.mock('./useSlashItems', () => ({
useSlashItems: () => [],
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
describe('Agent profile EditorCanvas', () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/src/routes/(main)/agent/profile/features/Header/index.test.tsx b/src/routes/(main)/agent/profile/features/Header/index.test.tsx
index 8a5ede9dfe1..29308325094 100644
--- a/src/routes/(main)/agent/profile/features/Header/index.test.tsx
+++ b/src/routes/(main)/agent/profile/features/Header/index.test.tsx
@@ -77,7 +77,8 @@ const renderMenuItems = (items: MockDropdownItem[]) =>
const getLatestExportedBlob = () => vi.mocked(URL.createObjectURL).mock.calls.at(-1)?.[0] as Blob;
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
DropdownMenu: ({
children,
items = [],
@@ -89,14 +90,6 @@ vi.mock('@lobehub/ui', () => ({
<div data-testid="agent-profile-menu">{renderMenuItems(items)}</div>
</div>
),
- Flexbox: ({ children }: PropsWithChildren) => <div>{children}</div>,
- Icon: () => <span />,
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: () => <button aria-label="more" type="button" />,
- confirmModal: vi.fn(),
- toast: { error: vi.fn(), success: vi.fn(), warning: vi.fn() },
}));
vi.mock('antd', async (importOriginal) => {
@@ -132,12 +125,6 @@ vi.mock('lucide-react', async (importOriginal) => ({
Trash: () => null,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('react-router', () => ({
useNavigate: () => mocks.navigate,
}));
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx
index c57bc96e565..3cf3994d4d3 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { act, render } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import AgentHeader from './AgentHeader';
@@ -57,36 +56,6 @@ const mocks = vi.hoisted(() => {
};
});
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
- Icon: () => <span />,
- Input: (props: Record<string, unknown>) => {
- mocks.inputProps.all.push(props);
- return <input readOnly disabled={props.disabled as boolean} value={props.value as string} />;
- },
- Skeleton: {
- Button: () => <div />,
- },
- Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: (props: Record<string, unknown>) => {
- mocks.actionIconProps.all.push(props);
- return (
- <button type="button" onClick={props.onClick as () => void}>
- {props.title as string}
- </button>
- );
- },
- Button: (props: Record<string, unknown>) => (
- <button type="button" onClick={props.onClick as () => void}>
- {props.children as ReactNode}
- </button>
- ),
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
-}));
-
vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
...((await importOriginal()) as Record<string, unknown>),
ActionIcon: (props: Record<string, unknown>) => {
@@ -97,15 +66,10 @@ vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
</button>
);
},
- Button: (props: Record<string, unknown>) => (
- <button type="button" onClick={props.onClick as () => void}>
- {props.children as ReactNode}
- </button>
- ),
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
}));
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
message: { error: vi.fn() },
}));
@@ -190,10 +154,6 @@ vi.mock('@/store/global/selectors', () => ({
},
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
describe('AgentHeader', () => {
beforeEach(() => {
vi.useFakeTimers();
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
index e811948eb51..a79aacfba21 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/HeterogeneousAgentStatusCard.test.tsx
@@ -49,7 +49,8 @@ vi.mock('@lobechat/heterogeneous-agents/client', () => ({
isRemoteHeterogeneousType: (type: string) => ['openclaw', 'hermes'].includes(type),
}));
-vi.mock('@lobehub/ui', () => ({
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
CopyButton: () => <button type="button">Copy</button>,
Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
Icon: () => <span>Icon</span>,
@@ -85,7 +86,8 @@ vi.mock('@lobehub/ui', () => ({
TooltipGroup: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
ActionIcon: ({
'aria-label': ariaLabel,
className,
@@ -162,23 +164,6 @@ vi.mock('@lobehub/ui/base-ui', () => ({
Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
}));
-vi.mock('antd-style', () => ({
- createStaticStyles: () => ({
- card: 'card',
- label: 'label',
- path: 'path',
- }),
- cssVar: new Proxy({}, { get: (_, key) => `var(--${String(key)})` }),
-}));
-
-vi.mock('lucide-react', () => ({
- CheckCircle2: () => null,
- Loader2Icon: () => null,
- PencilLine: () => null,
- RefreshCw: () => null,
- XCircle: () => null,
-}));
-
vi.mock('react-i18next', () => ({
useTranslation: () => ({
t: (key: string, options?: { name?: string }) =>
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx
index a3e0f64454d..4c8e0a49dcc 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentDevicePolicy.test.tsx
@@ -1,5 +1,6 @@
+import type * as BaseUI from '@lobehub/ui/base-ui';
import { act, render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
+import type { ComponentType } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import WorkspaceAgentDevicePolicy from './WorkspaceAgentDevicePolicy';
@@ -21,29 +22,19 @@ const testState = vi.hoisted(() => ({
mutateDevices: vi.fn(),
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
+const selectPropsSpy = vi.hoisted(() => vi.fn());
-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
- ...((await importOriginal()) as Record<string, unknown>),
- Select: ({
- disabled,
- loading,
- popupMatchSelectWidth,
- }: {
- disabled?: boolean;
- loading?: boolean;
- popupMatchSelectWidth?: boolean | number;
- }) => (
- <button
- data-popup-match-select-width={String(popupMatchSelectWidth)}
- disabled={disabled || loading}
- role="combobox"
- />
- ),
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
-}));
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
+ const actual = await importOriginal<typeof BaseUI>();
+ const ActualSelect = actual.Select as ComponentType<Record<string, unknown>>;
+ return {
+ ...actual,
+ Select: (props: Record<string, unknown>) => {
+ selectPropsSpy(props);
+ return <ActualSelect {...props} />;
+ },
+ };
+});
vi.mock('@/features/DeviceManager/useDeviceList', () => ({
useDeviceList: () => ({
@@ -64,6 +55,7 @@ describe('WorkspaceAgentDevicePolicy', () => {
testState.agent.agentMap['agent-1'].visibility = 'public';
testState.agent.updateAgentConfigById.mockReset();
testState.mutateDevices.mockReset();
+ selectPropsSpy.mockClear();
});
it('renders the environment picker without a member-switch control', () => {
@@ -94,9 +86,10 @@ describe('WorkspaceAgentDevicePolicy', () => {
expect(screen.queryByText('settingAgent.devicePolicy.defaultTarget')).toBeNull();
expect(screen.queryByRole('switch')).toBeNull();
- const select = screen.getByRole('combobox') as HTMLButtonElement;
- expect(select.disabled).toBe(false);
- expect(select.dataset.popupMatchSelectWidth).toBe('true');
+ const selectProps = selectPropsSpy.mock.lastCall?.[0] as Record<string, unknown>;
+ expect(selectProps.popupMatchSelectWidth).toBe(true);
+ expect(selectProps.disabled).toBeFalsy();
+ expect(selectProps.loading).toBeFalsy();
await act(async () => finishSave?.());
});
diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentModelPolicy.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentModelPolicy.test.tsx
index 98e28248e66..41db57a0128 100644
--- a/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentModelPolicy.test.tsx
+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/WorkspaceAgentModelPolicy.test.tsx
@@ -20,14 +20,6 @@ const testState = vi.hoisted(() => ({
},
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
-vi.mock('@/hooks/usePermission', () => ({
- usePermission: () => ({ allowed: true }),
-}));
-
vi.mock('@/features/ModelSelect', () => ({
default: () => <div data-testid="model-select" />,
}));
diff --git a/src/routes/(main)/community/(detail)/_layout/Header.test.tsx b/src/routes/(main)/community/(detail)/_layout/Header.test.tsx
index 299f602cc75..1ed8b888b3a 100644
--- a/src/routes/(main)/community/(detail)/_layout/Header.test.tsx
+++ b/src/routes/(main)/community/(detail)/_layout/Header.test.tsx
@@ -9,22 +9,6 @@ const mocks = vi.hoisted(() => ({
useUserProfile: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ onClick }: { onClick?: () => void }) => (
- <button data-testid="back-button" onClick={onClick} />
- ),
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: ({ onClick }: { onClick?: () => void }) => (
- <button data-testid="back-button" onClick={onClick} />
- ),
-}));
-
vi.mock('@/features/NavHeader', () => ({
default: ({ left, right }: { left?: React.ReactNode; right?: React.ReactNode }) => (
<header>
diff --git a/src/routes/(main)/community/(detail)/organization/features/Header/index.test.tsx b/src/routes/(main)/community/(detail)/organization/features/Header/index.test.tsx
index 5e6eefbf18d..e01b4a114b6 100644
--- a/src/routes/(main)/community/(detail)/organization/features/Header/index.test.tsx
+++ b/src/routes/(main)/community/(detail)/organization/features/Header/index.test.tsx
@@ -1,7 +1,5 @@
// @vitest-environment happy-dom
import { render, screen } from '@testing-library/react';
-import type { ReactNode } from 'react';
-import { createElement } from 'react';
import { describe, expect, it, vi } from 'vitest';
import {
@@ -10,20 +8,6 @@ import {
} from '../DetailProvider';
import OrganizationHeader from './index';
-vi.mock('@lobehub/ui/base-ui', () => ({
- ActionIcon: () => <button type="button" />,
- Avatar: ({ avatar, alt }: { alt?: string; avatar?: string }) => (
- <span>{alt ?? String(avatar ?? '')}</span>
- ),
- Tag: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
- Text: ({ as = 'span', children }: { as?: string; children?: ReactNode }) =>
- createElement(as, undefined, children),
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/routes/(main)/community/(detail)/features/FollowButton', () => ({
default: ({ userId }: { userId: number }) => <button>follow-{userId}</button>,
}));
diff --git a/src/routes/(main)/community/(detail)/workspace/features/Header/index.test.tsx b/src/routes/(main)/community/(detail)/workspace/features/Header/index.test.tsx
index 2b731f42a77..2381ef379a3 100644
--- a/src/routes/(main)/community/(detail)/workspace/features/Header/index.test.tsx
+++ b/src/routes/(main)/community/(detail)/workspace/features/Header/index.test.tsx
@@ -6,10 +6,6 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { type WorkspaceDetailContextConfig, WorkspaceDetailProvider } from '../DetailProvider';
import WorkspaceHeader from './index';
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('./Banner', () => ({
default: () => <div data-testid="workspace-banner" />,
}));
diff --git a/src/routes/(main)/community/(detail)/workspace/features/WorkspaceContent.test.tsx b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceContent.test.tsx
index 986c0ba878d..e0c001d2bb7 100644
--- a/src/routes/(main)/community/(detail)/workspace/features/WorkspaceContent.test.tsx
+++ b/src/routes/(main)/community/(detail)/workspace/features/WorkspaceContent.test.tsx
@@ -5,10 +5,6 @@ import { describe, expect, it, vi } from 'vitest';
import { type WorkspaceDetailContextConfig, WorkspaceDetailProvider } from './DetailProvider';
import WorkspaceContent from './WorkspaceContent';
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('../../user/features/useUserDetail', () => ({
useUserDetail: () => ({ handleStatusChange: vi.fn() }),
}));
diff --git a/src/routes/(main)/community/(list)/agent/features/List/Item.test.tsx b/src/routes/(main)/community/(list)/agent/features/List/Item.test.tsx
index dcb7b386b46..84983246085 100644
--- a/src/routes/(main)/community/(list)/agent/features/List/Item.test.tsx
+++ b/src/routes/(main)/community/(list)/agent/features/List/Item.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment happy-dom
import { fireEvent, render, screen } from '@testing-library/react';
-import type { MouseEventHandler, ReactNode } from 'react';
+import type { ReactNode } from 'react';
import { describe, expect, it, vi } from 'vitest';
import type { DiscoverAssistantItem } from '@/types/discover';
@@ -11,36 +11,6 @@ const mocks = vi.hoisted(() => ({
navigate: vi.fn(),
}));
-vi.mock('@lobehub/ui', () => ({
- Avatar: ({ avatar }: { avatar?: string }) => <div data-avatar={avatar} />,
- Block: ({
- children,
- onClick,
- }: {
- children?: ReactNode;
- onClick?: MouseEventHandler<HTMLDivElement>;
- }) => (
- <div data-testid="assistant-item" onClick={onClick}>
- {children}
- </div>
- ),
- Flexbox: ({
- children,
- onClick,
- }: {
- children?: ReactNode;
- onClick?: MouseEventHandler<HTMLDivElement>;
- }) => <div onClick={onClick}>{children}</div>,
- Icon: () => <span />,
- Tag: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
- Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/components/PublishedTime', () => ({
default: ({ date }: { date?: string }) => <span>{date}</span>,
}));
diff --git a/src/routes/(main)/community/features/UserAvatar/index.test.tsx b/src/routes/(main)/community/features/UserAvatar/index.test.tsx
index 30596b67b62..9005dc8abec 100644
--- a/src/routes/(main)/community/features/UserAvatar/index.test.tsx
+++ b/src/routes/(main)/community/features/UserAvatar/index.test.tsx
@@ -12,27 +12,6 @@ const mocks = vi.hoisted(() => ({
},
}));
-vi.mock('@lobehub/ui', () => ({
- Skeleton: {
- Avatar: () => <div data-testid="avatar-skeleton" />,
- },
-}));
-
-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
- const actual = (await importOriginal()) as Record<string, unknown>;
- return {
- ...actual,
- Avatar: ({ avatar, onClick }: { avatar?: string | null; onClick?: () => void }) => (
- <button data-avatar={avatar ?? ''} data-testid="community-user-avatar" onClick={onClick} />
- ),
- Button: ({ children }: { children?: string }) => <button>{children}</button>,
- };
-});
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/business/client/hooks/useCommunityWorkspaceProfile', () => ({
useCommunityWorkspaceProfile: () => mocks.communityWorkspaceProfile,
}));
@@ -69,6 +48,6 @@ describe('Community UserAvatar', () => {
it('uses the provided avatar override before workspace fallback', () => {
render(<UserAvatar avatarOverride={'🏢'} />);
- expect(screen.getByTestId('community-user-avatar')).toHaveAttribute('data-avatar', '🏢');
+ expect(screen.getByRole('img', { name: '🏢' })).toBeInTheDocument();
});
});
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.test.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.test.tsx
index fba8f11fa16..e2b5786bcec 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.test.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/List/Item/useDropdownMenu.test.tsx
@@ -11,17 +11,8 @@ const permissionMock = vi.hoisted(() => ({
edit_own_content: true,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Icon: () => null,
-}));
-
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
message: {
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx
index d2f3bbd8d7e..11ae9ff5251 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ThreadList/ThreadItem/useDropdownMenu.test.tsx
@@ -6,17 +6,8 @@ import { describe, expect, it, vi } from 'vitest';
import { useThreadItemDropdownMenu } from './useDropdownMenu';
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Icon: () => null,
-}));
-
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
modal: {
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
index 402ec911720..5b7eadf2bcf 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/useDropdownMenu.test.tsx
@@ -2,7 +2,6 @@
* @vitest-environment happy-dom
*/
import { renderHook } from '@testing-library/react';
-import type { ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { useTopicActionsDropdownMenu } from './useDropdownMenu';
@@ -43,22 +42,14 @@ vi.mock('@/store/user', () => ({
useUserStore: () => userMock.currentUserId,
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
confirmModal: confirmModalMock,
toast: messageMock,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Icon: () => null,
-}));
-
-vi.mock('antd', () => ({
+vi.mock('antd', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
App: {
useApp: () => ({
message: messageMock,
@@ -68,7 +59,6 @@ vi.mock('antd', () => ({
},
}),
},
- Upload: ({ children }: { children: ReactNode }) => <>{children}</>,
}));
vi.mock('@/hooks/usePermission', () => ({
diff --git a/src/routes/(main)/group/features/Conversation/Header/ShareButton/index.test.tsx b/src/routes/(main)/group/features/Conversation/Header/ShareButton/index.test.tsx
index 9fb62ad0df0..db038fced13 100644
--- a/src/routes/(main)/group/features/Conversation/Header/ShareButton/index.test.tsx
+++ b/src/routes/(main)/group/features/Conversation/Header/ShareButton/index.test.tsx
@@ -1,8 +1,9 @@
/**
* @vitest-environment happy-dom
*/
+import type * as BaseUI from '@lobehub/ui/base-ui';
import { render } from '@testing-library/react';
-import type { ReactNode } from 'react';
+import type { ComponentProps, ReactNode } from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import ShareButton from './index';
@@ -16,22 +17,18 @@ const mocks = vi.hoisted(() => ({
},
}));
-vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
- ...((await importOriginal()) as Record<string, unknown>),
- ActionIcon: ({
- disabled,
- onClick,
- title,
- }: {
- disabled?: boolean;
- onClick?: () => void;
- title?: string;
- }) => (
- <button data-testid="share-button" disabled={disabled} title={title} onClick={onClick}>
- {title}
- </button>
- ),
-}));
+const actionIconPropsSpy = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => {
+ const actual = await importOriginal<typeof BaseUI>();
+ return {
+ ...actual,
+ ActionIcon: (props: ComponentProps<typeof actual.ActionIcon>) => {
+ actionIconPropsSpy(props);
+ return <actual.ActionIcon {...props} />;
+ },
+ };
+});
vi.mock('@/libs/next/dynamic', () => ({
default: () =>
@@ -40,12 +37,6 @@ vi.mock('@/libs/next/dynamic', () => ({
},
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
vi.mock('@/features/ShareModal', () => ({
useShareModal: () => ({
openShareModal: vi.fn(),
@@ -78,15 +69,21 @@ describe('Group Conversation ShareButton', () => {
mocks.activeTopicId = 'topic-1';
mocks.enableBusinessFeatures = true;
mocks.permission.allowed = true;
+ actionIconPropsSpy.mockClear();
});
it('does not open share popover for workspace viewers', () => {
mocks.permission.allowed = false;
- const { queryByTestId, getByTestId } = render(<ShareButton />);
+ const { queryByTestId } = render(<ShareButton />);
- expect(getByTestId('share-button')).toBeDisabled();
- expect(getByTestId('share-button')).toHaveAttribute('title', 'requires member');
+ expect(actionIconPropsSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ disabled: true,
+ onClick: undefined,
+ title: 'requires member',
+ }),
+ );
expect(queryByTestId('share-popover')).toBeNull();
});
});
diff --git a/src/routes/(mobile)/me/settings/features/useCategory.test.tsx b/src/routes/(mobile)/me/settings/features/useCategory.test.tsx
index 4d7ca64868f..64f2084d0a9 100644
--- a/src/routes/(mobile)/me/settings/features/useCategory.test.tsx
+++ b/src/routes/(mobile)/me/settings/features/useCategory.test.tsx
@@ -26,12 +26,6 @@ vi.mock('react-router', () => ({
useNavigate: () => navigate,
}));
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({
- t: (key: string) => key,
- }),
-}));
-
const createWrapper = (showProvider: boolean) => {
const Wrapper = ({ children }: { children: ReactNode }) => (
<Provider
diff --git a/src/routes/(mobile)/settings/_layout/Header.test.tsx b/src/routes/(mobile)/settings/_layout/Header.test.tsx
index 7b156972b3f..f08205a4dd4 100644
--- a/src/routes/(mobile)/settings/_layout/Header.test.tsx
+++ b/src/routes/(mobile)/settings/_layout/Header.test.tsx
@@ -1,29 +1,10 @@
-import React from 'react';
-import { renderToStaticMarkup } from 'react-dom/server';
+// @vitest-environment happy-dom
+import { render, screen, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import { describe, expect, it, vi } from 'vitest';
import Header from './Header';
-vi.mock('@lobehub/ui', () => ({
- Flexbox: ({ children }: { children?: React.ReactNode }) =>
- React.createElement(React.Fragment, undefined, children),
-}));
-
-vi.mock('@lobehub/ui/mobile', () => {
- const ChatHeader = ({ center }: { center?: React.ReactNode }) =>
- React.createElement('header', undefined, center);
-
- ChatHeader.Title = ({ title }: { title?: React.ReactNode }) =>
- React.createElement(React.Fragment, undefined, title);
-
- return { ChatHeader };
-});
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
useWorkspaceAwareNavigate: () => vi.fn(),
}));
@@ -35,7 +16,7 @@ vi.mock('@/store/session', () => ({
}));
const renderHeader = (tab: string) =>
- renderToStaticMarkup(
+ render(
<MemoryRouter initialEntries={[`/acme/settings/${tab}`]}>
<Header />
</MemoryRouter>,
@@ -51,9 +32,8 @@ describe('mobile settings Header', () => {
['devices', 'setting:tab.devices'],
['service-model', 'setting:tab.serviceModel'],
])('resolves the workspace %s title', (tab, title) => {
- const html = renderHeader(tab);
+ renderHeader(tab);
- expect(html).toContain('<header>');
- expect(html).toContain(`>${title}</span></header>`);
+ expect(within(screen.getByRole('banner')).getByText(title)).toBeInTheDocument();
});
});
diff --git a/src/services/__tests__/_auth.test.ts b/src/services/__tests__/_auth.test.ts
index 4df93d7a52e..973b27cb7cc 100644
--- a/src/services/__tests__/_auth.test.ts
+++ b/src/services/__tests__/_auth.test.ts
@@ -16,9 +16,6 @@ const mockMistralAPIKey = 'mistral-api-key';
const mockOpenRouterAPIKey = 'openrouter-api-key';
const mockTogetherAIAPIKey = 'togetherai-api-key';
-// mock the traditional zustand
-vi.mock('zustand/traditional');
-
const mockCryptoValue = (value: number) => {
vi.stubGlobal('crypto', {
getRandomValues: vi.fn((array: Uint32Array) => {
diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.ts
index 4e2b5ab385c..c0d8af99177 100644
--- a/src/store/agent/slices/agent/action.test.ts
+++ b/src/store/agent/slices/agent/action.test.ts
@@ -15,9 +15,6 @@ import { withSWR } from '~test-utils';
import { useAgentStore } from '../../store';
-// Mock zustand/traditional for store testing
-vi.mock('zustand/traditional');
-
// Mock agentService
vi.mock('@/services/agent', () => ({
AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT: 12,
@@ -42,8 +39,9 @@ vi.mock('@/services/agentDocument', () => ({
resolveAgentDocumentsContext: vi.fn(),
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- toast: { error: vi.fn() },
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
}));
// Mock sessionStore
diff --git a/src/store/agent/slices/artwork/action.test.ts b/src/store/agent/slices/artwork/action.test.ts
index 8db3d58acd9..60adb151aab 100644
--- a/src/store/agent/slices/artwork/action.test.ts
+++ b/src/store/agent/slices/artwork/action.test.ts
@@ -8,8 +8,6 @@ import { AsyncTaskStatus } from '@/types/asyncTask';
import { useAgentStore } from '../../store';
-vi.mock('zustand/traditional');
-
vi.mock('@/services/generation', () => ({
generationService: { deleteGeneration: vi.fn(), getGenerationStatus: vi.fn() },
}));
diff --git a/src/store/agent/slices/knowledge/action.test.ts b/src/store/agent/slices/knowledge/action.test.ts
index 6a3f96663d5..f6e10c208b0 100644
--- a/src/store/agent/slices/knowledge/action.test.ts
+++ b/src/store/agent/slices/knowledge/action.test.ts
@@ -7,9 +7,6 @@ import { withSWR } from '~test-utils';
import { useAgentStore } from '../../store';
-// Mock zustand/traditional for store testing
-vi.mock('zustand/traditional');
-
// Mock agentService
vi.mock('@/services/agent', () => ({
AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT: 12,
diff --git a/src/store/agent/slices/plugin/action.test.ts b/src/store/agent/slices/plugin/action.test.ts
index f36b9b02f57..543e22428d1 100644
--- a/src/store/agent/slices/plugin/action.test.ts
+++ b/src/store/agent/slices/plugin/action.test.ts
@@ -5,9 +5,6 @@ import { agentService } from '@/services/agent';
import { useAgentStore } from '../../store';
-// Mock zustand/traditional for store testing
-vi.mock('zustand/traditional');
-
// Mock agentService
vi.mock('@/services/agent', () => ({
AVAILABLE_AGENTS_CONTEXT_QUERY_LIMIT: 12,
diff --git a/src/store/aiInfra/slices/aiModel/action.test.ts b/src/store/aiInfra/slices/aiModel/action.test.ts
index 62809303c8f..7d92fbaaca7 100644
--- a/src/store/aiInfra/slices/aiModel/action.test.ts
+++ b/src/store/aiInfra/slices/aiModel/action.test.ts
@@ -13,8 +13,6 @@ import { withSWR } from '~test-utils';
import { useAiInfraStore as useStore } from '../../store';
import { aiModelSelectors } from './selectors';
-vi.mock('zustand/traditional');
-
vi.mock('i18next', async (importOriginal) => {
const actual = await importOriginal<typeof I18nextModule>();
return {
@@ -23,8 +21,9 @@ vi.mock('i18next', async (importOriginal) => {
};
});
-vi.mock('@lobehub/ui/base-ui', () => ({
- toast: { error: vi.fn(), warning: vi.fn() },
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
}));
vi.mock('@/libs/swr', async (importOriginal) => {
diff --git a/src/store/chat/slices/agentRun/__tests__/ai-chat.integration.test.ts b/src/store/chat/slices/agentRun/__tests__/ai-chat.integration.test.ts
index c8b71e899d3..96581050cb9 100644
--- a/src/store/chat/slices/agentRun/__tests__/ai-chat.integration.test.ts
+++ b/src/store/chat/slices/agentRun/__tests__/ai-chat.integration.test.ts
@@ -9,8 +9,6 @@ import { operationSelectors } from '@/store/chat/selectors';
import { useChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-vi.mock('zustand/traditional');
-
describe('AI Chat Operation Integration Tests', () => {
beforeEach(() => {
act(() => {
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
index 0be8e93514c..eb8f5caffe6 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts
@@ -12,9 +12,6 @@ import { messageMapKey } from '../../../../utils/messageMapKey';
import { createMockMessage, createMockResolvedAgentConfig, TEST_IDS } from './fixtures';
import { resetTestEnvironment } from './helpers';
-// Keep zustand mock as it's needed globally
-vi.mock('zustand/traditional');
-
// Mock the tRPC client & agentRuntimeService so the import chain doesn't pull
// server-only code (cloud business packages, redis envs) into the test env.
vi.mock('@/libs/trpc/client', () => ({
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
index 841acf4295a..fabb3887eb4 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts
@@ -30,9 +30,6 @@ import { useChatStore } from '../../../../store';
import { createMockAgentConfig, createMockMessage, TEST_CONTENT, TEST_IDS } from './fixtures';
import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';
-// Keep zustand mock as it's needed globally
-vi.mock('zustand/traditional');
-
const executeHeterogeneousAgentMock = vi.hoisted(() => vi.fn());
const mockConstEnv = vi.hoisted(() => ({ isDesktop: false }));
const mockLocalFileService = vi.hoisted(() => ({
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
index c00b6faf949..d96e02bed4d 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/heterogeneousAgentExecutor.test.ts
@@ -41,7 +41,8 @@ const mockUpdateToolMessage = vi.fn();
const mockGetMessages = vi.fn();
const mockToastInfo = vi.fn();
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
toast: { info: (...args: unknown[]) => mockToastInfo(...args) },
}));
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
index 018878e1796..1f4a691d091 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.test.ts
@@ -94,8 +94,6 @@ const createMockRuntimeState = (operationId: string, status: AgentState['status'
},
});
-// Keep zustand mock as it's needed globally
-vi.mock('zustand/traditional');
vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () => ({
emitClientAgentSignalSourceEvent: agentSignalBridgeMock.emitClientAgentSignalSourceEvent,
}));
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingStates.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingStates.test.ts
index 8f36281b670..efba659346d 100644
--- a/src/store/chat/slices/agentRun/actions/__tests__/streamingStates.test.ts
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingStates.test.ts
@@ -5,9 +5,6 @@ import { useChatStore } from '../../../../store';
import { TEST_IDS } from './fixtures';
import { resetTestEnvironment } from './helpers';
-// Keep zustand mock as it's needed globally
-vi.mock('zustand/traditional');
-
beforeEach(() => {
resetTestEnvironment();
});
diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts
index 8fce165dc4b..933b6b361c7 100644
--- a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts
+++ b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts
@@ -5,9 +5,6 @@ import { lambdaClient } from '@/libs/trpc/client';
import { agentRuntimeClient } from '@/services/agentRuntime';
import { useChatStore } from '@/store/chat/store';
-// Keep zustand mock as it's needed globally
-vi.mock('zustand/traditional');
-
// Mock lambdaClient
vi.mock('@/libs/trpc/client', () => ({
lambdaClient: {
diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroupFlicker.test.tsx b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroupFlicker.test.tsx
index baef625b2c0..cf6cb976a18 100644
--- a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroupFlicker.test.tsx
+++ b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroupFlicker.test.tsx
@@ -14,9 +14,6 @@ import { agentRuntimeClient } from '@/services/agentRuntime';
import { useChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-// Keep zustand mock as it's needed globally for store reset between tests
-vi.mock('zustand/traditional');
-
vi.mock('@/libs/trpc/client', () => ({
lambdaClient: {
aiAgent: { execGroupAgent: { mutate: vi.fn() } },
diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/groupOrchestration.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/groupOrchestration.test.ts
index b8153c39afe..bee332d45e5 100644
--- a/src/store/chat/slices/aiAgent/actions/__tests__/groupOrchestration.test.ts
+++ b/src/store/chat/slices/aiAgent/actions/__tests__/groupOrchestration.test.ts
@@ -5,8 +5,6 @@ import { useClientDataSWR } from '@/libs/swr';
import { useAgentGroupStore } from '@/store/agentGroup';
import { useChatStore } from '@/store/chat/store';
-// Keep zustand mock as it's needed globally
-vi.mock('zustand/traditional');
vi.mock('@/libs/swr', () => ({
useClientDataSWR: vi.fn(),
}));
diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
index e1fc6efde7c..f426a44153c 100644
--- a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
+++ b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts
@@ -6,8 +6,6 @@ import { useChatStore } from '@/store/chat/store';
import { notifyDesktopHumanApprovalRequired } from '@/store/chat/utils/desktopNotification';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-// Keep zustand mock as it's needed globally
-vi.mock('zustand/traditional');
vi.mock('@/store/chat/utils/desktopNotification', () => ({
notifyDesktopAgentCompleted: vi.fn().mockResolvedValue(undefined),
notifyDesktopHumanApprovalRequired: vi.fn().mockResolvedValue(undefined),
diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.ts
index 30b4efa5b62..7c9d7820b31 100644
--- a/src/store/chat/slices/message/action.test.ts
+++ b/src/store/chat/slices/message/action.test.ts
@@ -1,6 +1,6 @@
import { type UIChatMessage } from '@lobechat/types';
import { TraceEventType } from '@lobechat/types';
-import * as lobeUIModules from '@lobehub/ui';
+import { copyToClipboard } from '@lobehub/ui';
import { act, renderHook } from '@testing-library/react';
import { type Mock } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -20,6 +20,11 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { useChatStore } from '../../store';
// Mock @/libs/swr mutate
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ copyToClipboard: vi.fn(),
+}));
+
vi.mock('@/libs/swr', async () => {
const actual = await vi.importActual('@/libs/swr');
return {
@@ -34,7 +39,6 @@ vi.stubGlobal(
vi.fn(() => Promise.resolve(new Response('mock'))),
);
-vi.mock('zustand/traditional');
// Mock service
vi.mock('@/services/message', () => ({
messageService: {
@@ -452,13 +456,12 @@ describe('chatMessage actions', () => {
const messageId = 'message-id';
const content = 'Test content';
const { result } = renderHook(() => useChatStore());
- const copyToClipboardSpy = vi.spyOn(lobeUIModules, 'copyToClipboard');
await act(async () => {
await result.current.copyMessage(messageId, content);
});
- expect(copyToClipboardSpy).toHaveBeenCalledWith(content);
+ expect(copyToClipboard).toHaveBeenCalledWith(content);
});
it('should call internal_traceMessage with correct parameters', async () => {
diff --git a/src/store/chat/slices/message/replaceMessages.orphanTool.regression.test.ts b/src/store/chat/slices/message/replaceMessages.orphanTool.regression.test.ts
index 26f0e307252..57c516ff264 100644
--- a/src/store/chat/slices/message/replaceMessages.orphanTool.regression.test.ts
+++ b/src/store/chat/slices/message/replaceMessages.orphanTool.regression.test.ts
@@ -17,7 +17,6 @@ vi.stubGlobal(
'fetch',
vi.fn(() => Promise.resolve(new Response('mock'))),
);
-vi.mock('zustand/traditional');
vi.mock('@/services/message', () => ({
messageService: {
createMessage: vi.fn(),
diff --git a/src/store/chat/slices/message/selectors/displayMessage.test.ts b/src/store/chat/slices/message/selectors/displayMessage.test.ts
index 10d165a8862..1fb9e7255f9 100644
--- a/src/store/chat/slices/message/selectors/displayMessage.test.ts
+++ b/src/store/chat/slices/message/selectors/displayMessage.test.ts
@@ -220,8 +220,22 @@ describe('displayMessageSelectors', () => {
},
activeAgentId: 'active-session',
});
+ act(() => {
+ useAgentStore.setState({
+ activeAgentId: 'inbox-agent',
+ builtinAgentIdMap: { inbox: 'inbox-agent' },
+ agentMap: {
+ 'inbox-agent': {
+ chatConfig: {
+ historyCount: 2,
+ enableHistoryCount: true,
+ },
+ model: 'abc',
+ },
+ },
+ });
+ });
- // Assume that the mainAIChatsWithHistoryConfig will return the last two messages
const expectedString = mockMessages
.slice(-2)
.map((m) => m.content)
diff --git a/src/store/chat/slices/operation/__tests__/integration.test.ts b/src/store/chat/slices/operation/__tests__/integration.test.ts
index f08f7b13e3a..47626db2536 100644
--- a/src/store/chat/slices/operation/__tests__/integration.test.ts
+++ b/src/store/chat/slices/operation/__tests__/integration.test.ts
@@ -9,8 +9,6 @@ import { operationSelectors } from '@/store/chat/slices/operation/selectors';
import { useChatStore } from '@/store/chat/store';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
-vi.mock('zustand/traditional');
-
describe('Operation Management Integration Tests', () => {
beforeEach(() => {
act(() => {
diff --git a/src/store/chat/slices/plugin/action.test.ts b/src/store/chat/slices/plugin/action.test.ts
index 96997db9a7a..1e30daa868d 100644
--- a/src/store/chat/slices/plugin/action.test.ts
+++ b/src/store/chat/slices/plugin/action.test.ts
@@ -33,8 +33,6 @@ vi.mock('@/utils/localStorage', () => {
return { AsyncLocalStorage };
});
-vi.mock('zustand/traditional');
-
// Mock messageService
vi.mock('@/services/message', () => ({
messageService: {
diff --git a/src/store/chat/slices/portal/action.test.ts b/src/store/chat/slices/portal/action.test.ts
index e2e788bc811..c2bbd3d87e2 100644
--- a/src/store/chat/slices/portal/action.test.ts
+++ b/src/store/chat/slices/portal/action.test.ts
@@ -19,8 +19,6 @@ const localFileTabId = ({
workingDirectory: string;
}) => createLocalFileTabId({ deviceId, filePath, workingDirectory });
-vi.mock('zustand/traditional');
-
describe('chatDockSlice', () => {
describe('pushPortalView', () => {
it('should push a new view onto the stack and open portal', () => {
diff --git a/src/store/chat/slices/thread/action.test.ts b/src/store/chat/slices/thread/action.test.ts
index ee8ebe60188..f939b8dc9e0 100644
--- a/src/store/chat/slices/thread/action.test.ts
+++ b/src/store/chat/slices/thread/action.test.ts
@@ -22,8 +22,6 @@ vi.mock('@/libs/swr', async () => {
};
});
-vi.mock('zustand/traditional');
-
// Mock version constants
vi.mock('@/const/version', () => ({
isDeprecatedEdition: false,
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index ab85b3cef69..106c4e870bc 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -30,7 +30,6 @@ vi.mock('@/libs/swr', async () => {
};
});
-vi.mock('zustand/traditional');
// Mock topicService 和 messageService
vi.mock('@/services/topic', () => ({
topicService: {
@@ -61,14 +60,6 @@ vi.mock('@/services/message', () => ({
},
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- toast: {
- error: vi.fn(),
- loading: vi.fn(() => ({ close: vi.fn() })),
- success: vi.fn(),
- },
-}));
-
vi.mock('i18next', () => ({
t: vi.fn((key, params) => (params.title ? key + '_' + params.title : key)),
}));
diff --git a/src/store/discover/slices/assistant/action.test.ts b/src/store/discover/slices/assistant/action.test.ts
index 7943ebc2b91..7cbe0718c7c 100644
--- a/src/store/discover/slices/assistant/action.test.ts
+++ b/src/store/discover/slices/assistant/action.test.ts
@@ -6,8 +6,6 @@ import { globalHelpers } from '@/store/global/helpers';
import { useDiscoverStore as useStore } from '../../store';
-vi.mock('zustand/traditional');
-
beforeEach(() => {
vi.clearAllMocks();
});
diff --git a/src/store/discover/slices/mcp/action.test.ts b/src/store/discover/slices/mcp/action.test.ts
index a15722e7503..8792225b384 100644
--- a/src/store/discover/slices/mcp/action.test.ts
+++ b/src/store/discover/slices/mcp/action.test.ts
@@ -6,8 +6,6 @@ import { globalHelpers } from '@/store/global/helpers';
import { useDiscoverStore as useStore } from '../../store';
-vi.mock('zustand/traditional');
-
beforeEach(() => {
vi.clearAllMocks();
});
diff --git a/src/store/discover/slices/model/action.test.ts b/src/store/discover/slices/model/action.test.ts
index c9f6ed5300d..5c02c63914c 100644
--- a/src/store/discover/slices/model/action.test.ts
+++ b/src/store/discover/slices/model/action.test.ts
@@ -6,8 +6,6 @@ import { globalHelpers } from '@/store/global/helpers';
import { useDiscoverStore as useStore } from '../../store';
-vi.mock('zustand/traditional');
-
beforeEach(() => {
vi.clearAllMocks();
});
diff --git a/src/store/discover/slices/plugin/action.test.ts b/src/store/discover/slices/plugin/action.test.ts
index 3632b02f757..b7acf9584a6 100644
--- a/src/store/discover/slices/plugin/action.test.ts
+++ b/src/store/discover/slices/plugin/action.test.ts
@@ -6,8 +6,6 @@ import { globalHelpers } from '@/store/global/helpers';
import { useDiscoverStore as useStore } from '../../store';
-vi.mock('zustand/traditional');
-
beforeEach(() => {
vi.clearAllMocks();
});
diff --git a/src/store/discover/slices/provider/action.test.ts b/src/store/discover/slices/provider/action.test.ts
index 7fa32cdb511..22795a501d8 100644
--- a/src/store/discover/slices/provider/action.test.ts
+++ b/src/store/discover/slices/provider/action.test.ts
@@ -6,8 +6,6 @@ import { globalHelpers } from '@/store/global/helpers';
import { useDiscoverStore as useStore } from '../../store';
-vi.mock('zustand/traditional');
-
beforeEach(() => {
vi.clearAllMocks();
});
diff --git a/src/store/discover/slices/skill/action.test.ts b/src/store/discover/slices/skill/action.test.ts
index f7e2d8b5a17..545e626c61a 100644
--- a/src/store/discover/slices/skill/action.test.ts
+++ b/src/store/discover/slices/skill/action.test.ts
@@ -7,8 +7,6 @@ import { SkillSorts } from '@/types/discover';
import { useDiscoverStore as useStore } from '../../store';
-vi.mock('zustand/traditional');
-
beforeEach(() => {
vi.clearAllMocks();
});
diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.ts
index 7bef3dd4e45..b41f7fea202 100644
--- a/src/store/file/slices/chat/action.test.ts
+++ b/src/store/file/slices/chat/action.test.ts
@@ -22,12 +22,9 @@ const mockAgentMode = ({
vi.spyOn(agentByIdSelectors, 'isAgentHeterogeneousById').mockReturnValue(() => heterogeneous);
};
-vi.mock('zustand/traditional');
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- toast: {
- error: vi.fn(),
- },
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
}));
vi.mock('@/services/rag', () => ({
diff --git a/src/store/file/slices/chunk/action.test.ts b/src/store/file/slices/chunk/action.test.ts
index 84f18b3482c..1e88914640c 100644
--- a/src/store/file/slices/chunk/action.test.ts
+++ b/src/store/file/slices/chunk/action.test.ts
@@ -5,8 +5,6 @@ import { ragService } from '@/services/rag';
import { useFileStore as useStore } from '../../store';
-vi.mock('zustand/traditional');
-
beforeEach(() => {
vi.clearAllMocks();
useStore.setState(
diff --git a/src/store/file/slices/document/action.test.ts b/src/store/file/slices/document/action.test.ts
index 19a7ab9680a..7a4b7fe7ef7 100644
--- a/src/store/file/slices/document/action.test.ts
+++ b/src/store/file/slices/document/action.test.ts
@@ -13,8 +13,6 @@ import { type ResourceItem } from '@/types/resource';
import { useFileStore as useStore } from '../../store';
import { getResourceQueryKey } from '../resource/utils';
-vi.mock('zustand/traditional');
-
vi.mock('@/services/document', () => ({
documentService: {
createDocument: vi.fn(),
@@ -184,8 +182,7 @@ describe('DocumentAction', () => {
const existingResource = createResourceFixture();
let resolveUpdate:
- | ((value: { historyAppended: boolean; id: string; savedAt?: string }) => void)
- | undefined;
+ ((value: { historyAppended: boolean; id: string; savedAt?: string }) => void) | undefined;
vi.mocked(documentService.updateDocument).mockImplementation(
() =>
new Promise((resolve) => {
diff --git a/src/store/file/slices/fileManager/action.test.ts b/src/store/file/slices/fileManager/action.test.ts
index e627bfd208e..ec462d93414 100644
--- a/src/store/file/slices/fileManager/action.test.ts
+++ b/src/store/file/slices/fileManager/action.test.ts
@@ -14,8 +14,6 @@ import { withSWR } from '~test-utils';
import { useFileStore as useStore } from '../../store';
import * as resourceHooks from '../resource/hooks';
-vi.mock('zustand/traditional');
-
// Mock i18next translation function
vi.mock('i18next', () => ({
t: (key: string, options?: any) => {
diff --git a/src/store/file/slices/tts/action.test.ts b/src/store/file/slices/tts/action.test.ts
index b946c531aee..f65f92caeea 100644
--- a/src/store/file/slices/tts/action.test.ts
+++ b/src/store/file/slices/tts/action.test.ts
@@ -6,8 +6,6 @@ import { createServerConfigStore } from '@/store/serverConfig/store';
import { useFileStore as useStore } from '../../store';
-vi.mock('zustand/traditional');
-
// mock the arrayBuffer
beforeAll(() => {
Object.defineProperty(File.prototype, 'arrayBuffer', {
diff --git a/src/store/file/slices/upload/action.test.ts b/src/store/file/slices/upload/action.test.ts
index cf0ba97d76c..1ca1b24dc64 100644
--- a/src/store/file/slices/upload/action.test.ts
+++ b/src/store/file/slices/upload/action.test.ts
@@ -10,11 +10,10 @@ import { getImageDimensions } from '@/utils/client/imageDimensions';
import { useFileStore as useStore } from '../../store';
-vi.mock('zustand/traditional');
-
// Mock necessary modules
-vi.mock('@lobehub/ui/base-ui', () => ({
- toast: { info: vi.fn() },
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
}));
vi.mock('@/business/client/handleFileUploadError', () => ({
diff --git a/src/store/global/action.test.ts b/src/store/global/action.test.ts
index 3f8a0e7ab32..ce70e02c34b 100644
--- a/src/store/global/action.test.ts
+++ b/src/store/global/action.test.ts
@@ -9,8 +9,6 @@ import { useGlobalStore } from '@/store/global/index';
import { createInitialSystemStatus, initialState } from '@/store/global/initialState';
import { withSWR } from '~test-utils';
-vi.mock('zustand/traditional');
-
vi.mock('@/utils/client/switchLang', () => ({
switchLang: vi.fn(),
}));
diff --git a/src/store/home/slices/sidebarUI/action.test.ts b/src/store/home/slices/sidebarUI/action.test.ts
index 3ec091cf149..f238b849ea8 100644
--- a/src/store/home/slices/sidebarUI/action.test.ts
+++ b/src/store/home/slices/sidebarUI/action.test.ts
@@ -16,7 +16,8 @@ import { getSessionStoreState } from '@/store/session';
import { useUserStore } from '@/store/user';
// Mock dependencies
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
toast: {
error: vi.fn(),
loading: vi.fn(() => ({ close: vi.fn() })),
diff --git a/src/store/library/slices/content/action.test.ts b/src/store/library/slices/content/action.test.ts
index 27e940ad4f3..d5f8bb49b41 100644
--- a/src/store/library/slices/content/action.test.ts
+++ b/src/store/library/slices/content/action.test.ts
@@ -5,8 +5,6 @@ import { useFileStore } from '@/store/file';
import { useKnowledgeBaseStore as useStore } from '../../store';
-vi.mock('zustand/traditional');
-
beforeEach(() => {
vi.clearAllMocks();
});
diff --git a/src/store/library/slices/crud/action.test.ts b/src/store/library/slices/crud/action.test.ts
index 9c3456f9971..34435a1429e 100644
--- a/src/store/library/slices/crud/action.test.ts
+++ b/src/store/library/slices/crud/action.test.ts
@@ -10,8 +10,6 @@ import { withSWR } from '~test-utils';
import { useKnowledgeBaseStore } from '../../store';
-vi.mock('zustand/traditional');
-
const mocks = vi.hoisted(() => ({
activeWorkspaceId: null as string | null,
}));
diff --git a/src/store/session/slices/session/action.test.ts b/src/store/session/slices/session/action.test.ts
index 002a5c684c8..ad1f523f0b7 100644
--- a/src/store/session/slices/session/action.test.ts
+++ b/src/store/session/slices/session/action.test.ts
@@ -30,7 +30,8 @@ vi.mock('@/services/chatGroup', () => ({
},
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
toast: {
error: vi.fn(),
loading: vi.fn(() => ({ close: vi.fn() })),
diff --git a/src/store/session/slices/sessionGroup/action.test.ts b/src/store/session/slices/sessionGroup/action.test.ts
index abf7c87dfc1..6a098a3752e 100644
--- a/src/store/session/slices/sessionGroup/action.test.ts
+++ b/src/store/session/slices/sessionGroup/action.test.ts
@@ -8,13 +8,6 @@ afterEach(() => {
vi.restoreAllMocks();
});
-vi.mock('@lobehub/ui/base-ui', () => ({
- toast: {
- loading: vi.fn(() => ({ close: vi.fn() })),
- success: vi.fn(),
- },
-}));
-
describe('createSessionGroupSlice', () => {
describe('addSessionGroup', () => {
it('should add a session group and refresh sessions', async () => {
diff --git a/src/store/task/slices/detail/action.test.ts b/src/store/task/slices/detail/action.test.ts
index c247b77fc4d..0a6efbaa3d6 100644
--- a/src/store/task/slices/detail/action.test.ts
+++ b/src/store/task/slices/detail/action.test.ts
@@ -38,8 +38,9 @@ vi.mock('@/components/AntdStaticMethods', () => ({
notification: { error: vi.fn() },
}));
-vi.mock('@lobehub/ui/base-ui', () => ({
- toast: { error: vi.fn(), success: vi.fn() },
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ ...(await import('~base-ui-stubs')).baseUiStubs,
}));
beforeEach(() => {
diff --git a/src/store/tool/slices/builtin/action.test.ts b/src/store/tool/slices/builtin/action.test.ts
index af8eb48491b..4f8aa3e313c 100644
--- a/src/store/tool/slices/builtin/action.test.ts
+++ b/src/store/tool/slices/builtin/action.test.ts
@@ -7,8 +7,6 @@ import { userService } from '@/services/user';
import { useToolStore } from '../../store';
-vi.mock('zustand/traditional');
-
describe('createBuiltinToolSlice', () => {
describe('transformApiArgumentsToAiState', () => {
it('should return early if the tool is already loading', async () => {
diff --git a/src/store/tool/slices/builtin/executors/index.lazy.test.ts b/src/store/tool/slices/builtin/executors/index.lazy.test.ts
index 3431e75e645..85bb41ea094 100644
--- a/src/store/tool/slices/builtin/executors/index.lazy.test.ts
+++ b/src/store/tool/slices/builtin/executors/index.lazy.test.ts
@@ -15,13 +15,17 @@ describe('builtin executor catalog loading', () => {
mocks.catalogEvaluated.mockClear();
});
- it('keeps executor implementations out of the registry shell import', async () => {
- const { registerBuiltinToolExecutors } = await import('./index');
+ it(
+ 'keeps executor implementations out of the registry shell import',
+ { timeout: 30_000 },
+ async () => {
+ const { registerBuiltinToolExecutors } = await import('./index');
- expect(mocks.catalogEvaluated).not.toHaveBeenCalled();
+ expect(mocks.catalogEvaluated).not.toHaveBeenCalled();
- await registerBuiltinToolExecutors();
+ await registerBuiltinToolExecutors();
- expect(mocks.catalogEvaluated).toHaveBeenCalledTimes(1);
- });
+ expect(mocks.catalogEvaluated).toHaveBeenCalledTimes(1);
+ },
+ );
});
diff --git a/src/store/tool/slices/lobehubSkillStore/action.test.ts b/src/store/tool/slices/lobehubSkillStore/action.test.ts
index e4ad408d588..1d0529f7cd5 100644
--- a/src/store/tool/slices/lobehubSkillStore/action.test.ts
+++ b/src/store/tool/slices/lobehubSkillStore/action.test.ts
@@ -10,8 +10,6 @@ import { useUserStore } from '@/store/user';
import { useToolStore } from '../../store';
import { LobehubSkillStatus } from './types';
-vi.mock('zustand/traditional');
-
beforeEach(() => {
vi.clearAllMocks();
useUserStore.setState({ isSignedIn: false });
diff --git a/src/store/tool/slices/mcpStore/action.test.ts b/src/store/tool/slices/mcpStore/action.test.ts
index b497e948ec2..5c75052a81c 100644
--- a/src/store/tool/slices/mcpStore/action.test.ts
+++ b/src/store/tool/slices/mcpStore/action.test.ts
@@ -44,9 +44,6 @@ vi.mock('@/libs/trpc/client', () => ({
},
}));
-// Keep zustand mock as it's needed globally
-vi.mock('zustand/traditional');
-
// Mock sleep to speed up tests
vi.mock('@/utils/sleep', () => ({
sleep: vi.fn().mockResolvedValue(undefined),
diff --git a/src/store/user/slices/auth/action.test.ts b/src/store/user/slices/auth/action.test.ts
index db8c265fd92..072d508204b 100644
--- a/src/store/user/slices/auth/action.test.ts
+++ b/src/store/user/slices/auth/action.test.ts
@@ -5,8 +5,6 @@ import { mutate } from '@/libs/swr';
import { userKeys } from '@/libs/swr/keys';
import { useUserStore } from '@/store/user';
-vi.mock('zustand/traditional');
-
// Mock @/libs/swr mutate
vi.mock('@/libs/swr', async () => {
const actual = await vi.importActual('@/libs/swr');
diff --git a/src/store/user/slices/common/action.test.ts b/src/store/user/slices/common/action.test.ts
index d76c285f907..7adcd01baf9 100644
--- a/src/store/user/slices/common/action.test.ts
+++ b/src/store/user/slices/common/action.test.ts
@@ -17,8 +17,6 @@ const swrMocks = vi.hoisted(() => ({
mutate: vi.fn(),
}));
-vi.mock('zustand/traditional');
-
vi.mock('@/libs/swr', async (importOriginal) => {
const actual = await importOriginal<typeof SWRLib>();
diff --git a/src/store/user/slices/onboarding/action.test.ts b/src/store/user/slices/onboarding/action.test.ts
index 2a6bb4a9415..2c7fa506930 100644
--- a/src/store/user/slices/onboarding/action.test.ts
+++ b/src/store/user/slices/onboarding/action.test.ts
@@ -8,8 +8,6 @@ import { useUserStore } from '@/store/user';
import { initialOnboardingState } from './initialState';
-vi.mock('zustand/traditional');
-
vi.mock('@/services/user', () => ({
userService: {
updateOnboarding: vi.fn(),
diff --git a/src/store/user/slices/settings/action.test.ts b/src/store/user/slices/settings/action.test.ts
index e4338c272f7..41d0bb76c71 100644
--- a/src/store/user/slices/settings/action.test.ts
+++ b/src/store/user/slices/settings/action.test.ts
@@ -9,8 +9,6 @@ import type { LobeAgentSettings } from '@/types/session';
import type { UserSettings } from '@/types/user/settings';
import { merge } from '@/utils/merge';
-vi.mock('zustand/traditional');
-
// Mock userService
vi.mock('@/services/user', () => ({
userService: {
diff --git a/tests/mocks/baseUiStubs.tsx b/tests/mocks/baseUiStubs.tsx
index 84d25e97343..f4e632df9af 100644
--- a/tests/mocks/baseUiStubs.tsx
+++ b/tests/mocks/baseUiStubs.tsx
@@ -81,7 +81,7 @@ export const createBaseUiStubs = () => ({
toast: Object.assign(vi.fn(), {
error: vi.fn(),
info: vi.fn(),
- loading: vi.fn(),
+ loading: vi.fn(() => ({ close: vi.fn(), update: vi.fn() })),
promise: vi.fn(),
success: vi.fn(),
warning: vi.fn(),
diff --git a/tests/setup.ts b/tests/setup.ts
index 59ad6edec54..a27a8545f7f 100644
--- a/tests/setup.ts
+++ b/tests/setup.ts
@@ -86,6 +86,27 @@ vi.mock('@/auth', () => ({
},
}));
+// Route zustand store creation through __mocks__/zustand/traditional.ts so every
+// store resets to its initial state between tests without per-file opt-in
+vi.mock('zustand/traditional');
+
+// Key-passthrough translations so component tests assert locale keys, not copy;
+// defaultValue still wins to match real t() fallback semantics. Tests needing
+// custom t/Trans behavior override with their own vi.mock
+vi.mock('react-i18next', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ useTranslation: () => ({
+ i18n: { changeLanguage: vi.fn(), language: 'en-US' },
+ t: (key: string, defaultValueOrOptions?: unknown, maybeOptions?: unknown) => {
+ if (typeof defaultValueOrOptions === 'string') return defaultValueOrOptions;
+ const options =
+ (defaultValueOrOptions as { defaultValue?: unknown } | undefined) ??
+ (maybeOptions as { defaultValue?: unknown } | undefined);
+ return typeof options?.defaultValue === 'string' ? options.defaultValue : key;
+ },
+ }),
+}));
+
type NativeButtonType = 'button' | 'submit' | 'reset';
type TestButtonIcon = ComponentType<{ size?: number }> | ReactNode;
diff --git a/vitest.config.mts b/vitest.config.mts
index 54469a0bde7..53496c0503d 100644
--- a/vitest.config.mts
+++ b/vitest.config.mts
@@ -162,6 +162,69 @@ export default defineConfig({
'**/packages/**',
'**/e2e/**',
],
+ /**
+ * `@lobehub/ui` is inlined below, so without prebundling every test file
+ * re-transforms and re-evaluates its whole ESM graph (~5s collect per file,
+ * the bulk of the suite's runtime). Prebundling it once via esbuild lets all
+ * workers share the cached chunk. The resolveId hacks from `plugins` are
+ * mirrored as esbuild plugins because dep optimization bypasses vite plugins.
+ */
+ deps: {
+ optimizer: {
+ web: {
+ enabled: true,
+ esbuildOptions: {
+ // CJS deps bundled into the chunk (antd-style) `require('react/jsx-runtime')`;
+ // esbuild's ESM __require shim only works if a real `require` is in scope
+ banner: {
+ js: 'import { createRequire as __vitestCreateRequire } from "node:module"; const require = __vitestCreateRequire(import.meta.url);',
+ },
+ jsx: 'automatic',
+ plugins: [
+ {
+ name: 'stub-lobehub-ui-motion-provider-esbuild',
+ setup(build: {
+ onResolve: (
+ options: { filter: RegExp },
+ callback: (args: { importer: string }) => { path: string } | null,
+ ) => void;
+ }) {
+ build.onResolve({ filter: /MotionProvider\/index\.m?js$/ }, (args) => {
+ if (!args.importer.includes('/@lobehub/ui/')) return null;
+ return {
+ path: resolve(__dirname, './tests/mocks/lobehubUiMotionProvider.tsx'),
+ };
+ });
+ build.onResolve({ filter: /^\.\/style\/index\.js$/ }, (args) => {
+ if (!args.importer.endsWith('/FluentEmoji/index.js')) return null;
+ return { path: resolve(dirname(args.importer), 'style.js') };
+ });
+ },
+ },
+ ],
+ },
+ // Setting `exclude` here replaces the root optimizeDeps.exclude; the node
+ // builtins must stay listed or vite swaps them for browser shims
+ exclude: ['crypto', 'util', 'tty'],
+ // Every imported subpath must be prebundled together: a subpath left to
+ // vite-node loads a second copy of the library whose MotionProvider /
+ // modal-stack contexts don't match the chunk's
+ include: [
+ '@lobehub/ui',
+ '@lobehub/ui/base-ui',
+ '@lobehub/ui/icons',
+ '@lobehub/ui/mobile',
+ '@lobehub/ui/chat',
+ '@lobehub/ui/awesome',
+ '@lobehub/ui/brand',
+ '@lobehub/ui/mdx',
+ '@lobehub/fluent-emoji',
+ 'motion',
+ 'motion/react',
+ ],
+ },
+ },
+ },
globals: true,
server: {
deps: {