1
8import { beforeEach, describe, expect, it } from "vitest";
9import { authStore, hasSession, useAuthStore } from "@/lib/auth-store";
10import type { User } from "@/lib/types";
11
12const user = { id: "u1", email: "a@b.c", name: "A" } as unknown as User;
13
14describe("auth-store", () => {
15 beforeEach(() => {
16
17 useAuthStore.setState({ user: null, accessToken: null, initializing: true });
18 });
19
20 it("setUser stores the user + token and ends initialization", () => {
21 authStore.setUser(user, "tok-1");
22 expect(authStore.user?.id).toBe("u1");
23 expect(authStore.accessToken).toBe("tok-1");
24 expect(useAuthStore.getState().initializing).toBe(false);
25 expect(hasSession()).toBe(true);
26 });
27
28 it("setAccessToken swaps the token without clearing the user", () => {
29 authStore.setUser(user, "tok-1");
30 authStore.setAccessToken("tok-2");
31 expect(authStore.accessToken).toBe("tok-2");
32 expect(authStore.user?.id).toBe("u1");
33 });
34
35 it("clear() resets user + token AND ends initialization (the logout fix)", () => {
36
37
38 authStore.setAccessToken("tok-1");
39 expect(useAuthStore.getState().initializing).toBe(true);
40
41 authStore.clear();
42 expect(authStore.user).toBeNull();
43 expect(authStore.accessToken).toBeNull();
44 expect(hasSession()).toBe(false);
45
46 expect(useAuthStore.getState().initializing).toBe(false);
47 });
48
49 it("clear() is idempotent when already signed out", () => {
50 authStore.clear();
51 authStore.clear();
52 expect(authStore.user).toBeNull();
53 expect(authStore.accessToken).toBeNull();
54 expect(useAuthStore.getState().initializing).toBe(false);
55 });
56});
57