Files
WonderQ-Project/WonderQ-MiniAPP/tests/auth.test.ts
2026-08-11 19:19:11 +08:00

63 lines
1.7 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from "vitest";
import {
clearAuthSession,
getAuthSession,
isLoggedIn,
maskPhone,
requireLogin,
saveAuthSession,
} from "@/lib/auth";
function installUniStorageMock() {
const storage = new Map<string, unknown>();
const navigateTo = vi.fn();
(globalThis as unknown as { uni: unknown }).uni = {
getStorageSync: (key: string) => storage.get(key),
setStorageSync: (key: string, value: unknown) => storage.set(key, value),
removeStorageSync: (key: string) => storage.delete(key),
navigateTo,
};
return { navigateTo, storage };
}
describe("miniapp auth helpers", () => {
beforeEach(() => {
vi.restoreAllMocks();
});
it("stores and clears the customer auth session", () => {
installUniStorageMock();
saveAuthSession({
token: "customer-token",
customer: { id: "customer-test", phoneMasked: "100****0000" },
});
expect(isLoggedIn()).toBe(true);
expect(getAuthSession()).toEqual({
token: "customer-token",
customer: { id: "customer-test", phoneMasked: "100****0000" },
});
clearAuthSession();
expect(isLoggedIn()).toBe(false);
expect(getAuthSession()).toBeNull();
});
it("redirects anonymous users to login with an encoded target", () => {
const { navigateTo } = installUniStorageMock();
const allowed = requireLogin("/pages/mine/index");
expect(allowed).toBe(false);
expect(navigateTo).toHaveBeenCalledWith({
url: "/pages/login/index?redirect=%2Fpages%2Fmine%2Findex",
});
});
it("masks phone numbers before rendering them on the client", () => {
expect(maskPhone("10000000000")).toBe("100****0000");
});
});