Files
UHD_Media_Tool/apps/web/app/lib/router-compat.test.ts
T

57 lines
2.6 KiB
TypeScript

import { createMemoryHistory, createRootRoute, createRoute, createRouter } from "@tanstack/react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import { navigateTo, parseUrlSearch, resolveTo, stringifyUrlSearch } from "./router-compat.tsx";
const current = { pathname: "/console/files", search: "?view=trash", hash: "#old" };
afterEach(() => vi.unstubAllGlobals());
describe("路由目标兼容", () => {
it("对象目标不继承未指定的查询和锚点", () => {
expect(resolveTo({ pathname: "/console/settings", hash: "#account/totp" }, current)).toBe(
"/console/settings#account/totp",
);
expect(resolveTo({ search: "?view=all" }, current)).toBe("/console/files?view=all");
});
it("仅有锚点的字符串目标保留当前查询", () => {
expect(resolveTo("#details", current)).toBe("/console/files?view=trash#details");
});
it("重复定位同一设置字段生成新的导航 key,后退恢复原来的业务 state", async () => {
vi.stubGlobal("window", { origin: "http://localhost" });
vi.stubGlobal("crypto", undefined);
const root = createRootRoute();
const settings = createRoute({ getParentRoute: () => root, path: "/console/settings" });
const history = createMemoryHistory({ initialEntries: ["/console/settings"] });
const router = createRouter({
routeTree: root.addChildren([settings]),
history,
isServer: false,
parseSearch: parseUrlSearch,
stringifySearch: stringifyUrlSearch,
});
const unsubscribe = history.subscribe(() => void router.load());
try {
await router.load();
const target = new URL("/console/settings?tag=one&tag=two#account/totp", window.origin);
const state = { field: "account.username", sheetFrom: "/console/settings" };
await navigateTo(router, target, { state, preventScrollReset: true });
const firstKey = router.state.location.state.__TSR_key;
const firstIndex = history.location.state.__TSR_index;
await navigateTo(router, target, { state, preventScrollReset: true });
expect(router.state.location.state.__TSR_key).not.toBe(firstKey);
expect(history.location.state.__TSR_index).toBe(firstIndex + 1);
expect(router.state.location.state).toMatchObject(state);
expect(router.state.location.search).toEqual({ tag: ["one", "two"] });
expect(router.state.location.hash).toBe("account/totp");
history.back();
await router.load();
expect(router.state.location.state.__TSR_key).toBe(firstKey);
expect(router.state.location.state).toMatchObject(state);
} finally {
unsubscribe();
}
});
});