文件
hyb-oa/client/tests/e2e/global-search.spec.ts
T

262 行
12 KiB
TypeScript

import { test, expect, type Page } from "@playwright/test";
import { ADMIN, login } from "./helpers/auth";
function envelope<T>(data: T) {
return {
requestId: "mock-request",
data,
};
}
async function mockSearchResults(page: Page) {
await page.route((url) => url.pathname.startsWith("/api/"), async (route) => {
const request = route.request();
const pathname = new URL(request.url()).pathname;
if (pathname === "/api/search") {
await route.fallback();
return;
}
if (pathname === "/api/auth/sso/providers") {
await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(envelope([])) });
return;
}
if (pathname === "/api/auth/wecom/config") {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(envelope({
enabled: false,
entryEnabled: false,
oauthEnabled: false,
corpId: "",
agentId: "",
loginUrl: null,
bindEnabled: false,
defaultReturnTo: "/portal",
status: "disabled",
statusReasons: [],
})),
});
return;
}
if (pathname === "/api/auth/login" || pathname === "/api/auth/refresh") {
await route.fulfill({
status: 200,
contentType: "application/json",
headers: { "set-cookie": "has_session=1; Path=/; SameSite=Lax" },
body: JSON.stringify(envelope({ accessToken: "mock-global-search-token", expiresIn: 900, mustChangePassword: false })),
});
return;
}
if (pathname === "/api/me") {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(envelope({
id: "admin-global-search",
employeeNo: ADMIN.employeeNo,
name: ADMIN.name,
phone: null,
email: ADMIN.identifier,
departmentId: "department-global-search",
directManagerId: null,
status: "active",
notificationPushEnabled: true,
roleCodes: ["admin"],
bankAccount: { bankName: null, bankInstitutionCode: null, accountNumberMasked: null },
profileCompleteness: {
hasEmergencyContact: true,
hasBankAccount: true,
hasAvatar: false,
hasIdNumber: false,
score: 50,
},
wecomBinding: null,
})),
});
return;
}
if (pathname === "/api/system/navigation") {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(envelope({
workspace: {
id: "workspace-global-search",
persisted: true,
profile: "small_team_internal",
orgMode: "single_company",
primaryEntryMode: "password",
notificationStrategy: "in_app",
devicePriority: "desktop",
moduleVisibility: {},
createdAt: null,
updatedAt: null,
updatedBy: null,
},
sections: {
main: [
{ key: "portal", href: "/portal", label: "工作台", icon: "home_app_logo", placement: "main", permissionCodes: [], featureFlagKey: null },
{ key: "reimbursements", href: "/reimbursements", label: "报销", icon: "receipt_long", placement: "main", permissionCodes: [], featureFlagKey: null },
{ key: "purchase", href: "/purchase-requests", label: "采购", icon: "shopping_cart", placement: "main", permissionCodes: [], featureFlagKey: null },
{ key: "assets", href: "/assets", label: "资产", icon: "inventory_2", placement: "main", permissionCodes: [], featureFlagKey: null },
],
admin: [],
backup: [],
},
recommendedRolePresets: [],
})),
});
return;
}
if (pathname === "/api/notifications") {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(envelope({ page: 1, pageSize: 1, total: 0, unreadOnly: true, unreadCount: 0, items: [] })),
});
return;
}
if (pathname === "/api/portal/home") {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(envelope({
workspace: { id: "workspace-global-search", persisted: true, profile: "small_team_internal" },
greeting: { name: ADMIN.name },
cards: [],
pendingTasks: { count: 0, href: "/workflow/tasks" },
myApplications: [],
riskSummary: null,
announcements: [],
quickLinks: [],
todayPresence: null,
teamPresence: null,
weeklyReport: null,
weeklySummary: null,
todoSummary: null,
projectSummary: null,
peopleLifecycle: null,
adoptionSummary: null,
recentActivities: [],
teamStatusBoard: [],
})),
});
return;
}
await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(envelope({})) });
});
await page.route("**/api/search?**", async (route) => {
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify(
envelope({
items: [
{ entityType: "employee", entityId: "employee-1", title: "王小明", subtitle: "E001 · 财务", status: "active", href: "/people/employee-1", matchedBy: "prefix", updatedAt: null },
{ entityType: "reimbursement", entityId: "reimbursement-1", title: "BX-001", subtitle: "办公室报销", status: "reviewing", href: "/reimbursements/reimbursement-1", matchedBy: "contains", updatedAt: null },
{ entityType: "leave", entityId: "leave-1", title: "请假 2026-03-24", subtitle: "年假", status: "approved", href: "/leave-requests", matchedBy: "contains", updatedAt: null },
{ entityType: "purchase_request", entityId: "purchase-1", title: "CG-001", subtitle: "办公椅采购", status: "reviewing", href: "/purchase-requests?id=legacy-wrong", matchedBy: "contains", updatedAt: null },
{ entityType: "travel_request", entityId: "travel-1", title: "CL-001", subtitle: "上海出差", status: "draft", href: "/travel-requests/travel-1", matchedBy: "contains", updatedAt: null },
{ entityType: "project", entityId: "project-1", title: "海音达试点", subtitle: "实施项目", status: "active", href: "/projects/project-1", matchedBy: "exact", updatedAt: null },
{ entityType: "announcement", entityId: "announcement-1", title: "本周通知", subtitle: "统一回填周报", status: null, href: "/announcements", matchedBy: "contains", updatedAt: null },
{ entityType: "asset", entityId: "asset-1", title: "ZC-001", subtitle: "MacBook Pro", status: "in_use", href: "/assets?highlight=legacy-wrong", matchedBy: "contains", updatedAt: null },
],
}),
),
});
});
}
test("E2E 全局搜索:按钮打开后按分组展示结果并支持点击跳转", async ({ page }) => {
await mockSearchResults(page);
await login(page, ADMIN);
await page.goto("/portal");
await expect(page.getByTestId("global-search-trigger")).toBeVisible();
await page.getByTestId("global-search-trigger").click();
await expect(page.getByRole("heading", { name: "全局搜索" })).toBeVisible();
const searchResponse = page.waitForResponse((response) => response.url().includes("/api/search?"));
await page.getByPlaceholder("搜索人员、项目、合同、公告、资产、请假、报销、周报、事项").fill("海音");
await searchResponse;
await expect(page.getByRole("heading", { name: "人员" })).toBeVisible();
await expect(page.getByRole("heading", { name: "业务单据" })).toBeVisible();
await expect(page.getByRole("heading", { name: "项目与公告" })).toBeVisible();
await expect(page.getByRole("heading", { name: "其他" })).toBeVisible();
await expect(page.getByRole("button", { name: /BX-001/ })).toBeVisible();
await expect(page.getByRole("button", { name: /请假 2026-03-24/ })).toBeVisible();
await expect(page.getByRole("button", { name: /CG-001/ })).toBeVisible();
await expect(page.getByRole("button", { name: /CL-001/ })).toHaveCount(0);
await expect(page.getByText("查看更多结果")).toBeVisible();
await page.getByRole("button", { name: /BX-001/ }).click();
await expect(page).toHaveURL(/\/reimbursements\/reimbursement-1/);
});
test("E2E 全局搜索:查看更多结果会关闭弹窗并跳到分组列表页", async ({ page }) => {
await mockSearchResults(page);
await login(page, ADMIN);
await page.goto("/portal");
await page.getByTestId("global-search-trigger").click();
await expect(page.getByRole("heading", { name: "全局搜索" })).toBeVisible();
const searchResponse = page.waitForResponse((response) => response.url().includes("/api/search?"));
await page.getByPlaceholder("搜索人员、项目、合同、公告、资产、请假、报销、周报、事项").fill("海音");
await searchResponse;
const documentsSection = page.locator("section").filter({ has: page.getByRole("heading", { name: "业务单据" }) });
await expect(documentsSection.getByRole("button", { name: "查看更多结果" })).toBeVisible();
await documentsSection.getByRole("button", { name: "查看更多结果" }).click();
await expect(page).toHaveURL(/\/reimbursements$/);
await expect(page.getByRole("heading", { name: "全局搜索" })).not.toBeVisible();
});
test("E2E 全局搜索:采购与资产忽略旧 href 并使用实体 canonical 路径", async ({ page }) => {
await mockSearchResults(page);
await login(page, ADMIN);
await page.goto("/portal");
await page.getByTestId("global-search-trigger").click();
const purchaseSearchResponse = page.waitForResponse((response) => response.url().includes("/api/search?"));
await page.getByPlaceholder("搜索人员、项目、合同、公告、资产、请假、报销、周报、事项").fill("海音");
await purchaseSearchResponse;
await page.getByRole("button", { name: /CG-001/ }).click();
await expect(page).toHaveURL(/\/purchase-requests\/purchase-1$/);
await page.goto("/portal");
await page.getByTestId("global-search-trigger").click();
const assetSearchResponse = page.waitForResponse((response) => response.url().includes("/api/search?"));
await page.getByPlaceholder("搜索人员、项目、合同、公告、资产、请假、报销、周报、事项").fill("海音");
await assetSearchResponse;
await page.getByRole("button", { name: /ZC-001/ }).click();
await expect(page).toHaveURL(/\/assets\/asset-1$/);
});
test("E2E 全局搜索:Ctrl+K 和 Cmd+K 可打开搜索弹窗", async ({ page }) => {
await mockSearchResults(page);
await login(page, ADMIN);
await page.goto("/portal");
await expect(page.getByTestId("global-search-trigger")).toBeVisible();
await page.evaluate(() => {
document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "k", ctrlKey: true, bubbles: true, cancelable: true }));
});
await expect(page.getByRole("heading", { name: "全局搜索" })).toBeVisible();
await page.getByRole("button", { name: "关闭" }).click();
await expect(page.getByRole("heading", { name: "全局搜索" })).not.toBeVisible();
await page.evaluate(() => {
document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "k", metaKey: true, bubbles: true, cancelable: true }));
});
await expect(page.getByRole("heading", { name: "全局搜索" })).toBeVisible();
});