101 lines
3.1 KiB
JavaScript
101 lines
3.1 KiB
JavaScript
// @vitest-environment node
|
|
|
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { createPinia, setActivePinia } from "pinia";
|
|
|
|
vi.mock("../src/services/apiClient.js", () => ({
|
|
default: {
|
|
get: vi.fn(),
|
|
post: vi.fn(() => Promise.resolve({})),
|
|
},
|
|
}));
|
|
|
|
import apiClient from "../src/services/apiClient.js";
|
|
import { useAuthStore } from "../src/stores/authStore.js";
|
|
|
|
describe("Auth Store", () => {
|
|
beforeEach(() => {
|
|
setActivePinia(createPinia());
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
it("should initialize with no user", () => {
|
|
const store = useAuthStore();
|
|
expect(store.isAuthenticated).toBe(false);
|
|
expect(store.user).toBeNull();
|
|
});
|
|
|
|
it("should store user data with setSession", () => {
|
|
const store = useAuthStore();
|
|
const mockUser = {
|
|
id: "123",
|
|
email: "test@example.com",
|
|
username: "testuser",
|
|
permissions: ["space.demo.note.create"],
|
|
};
|
|
|
|
store.setSession({ user: mockUser });
|
|
|
|
expect(store.isAuthenticated).toBe(true);
|
|
expect(store.user).toEqual(mockUser);
|
|
expect(store.hasPermission("space.demo.note.create")).toBe(true);
|
|
});
|
|
|
|
it("should login and persist returned user", async () => {
|
|
const store = useAuthStore();
|
|
apiClient.post.mockResolvedValueOnce({
|
|
data: {
|
|
user: {
|
|
id: "123",
|
|
email: "test@example.com",
|
|
username: "testuser",
|
|
permissions: [],
|
|
},
|
|
},
|
|
});
|
|
|
|
const result = await store.login(" test@example.com ", "password123");
|
|
|
|
expect(apiClient.post).toHaveBeenCalledWith("/api/v1/auth/login", {
|
|
email: "test@example.com",
|
|
password: "password123",
|
|
});
|
|
expect(result.user.username).toBe("testuser");
|
|
expect(store.user?.username).toBe("testuser");
|
|
});
|
|
|
|
it("should clear user data on logout", async () => {
|
|
const store = useAuthStore();
|
|
store.setSession({
|
|
user: {
|
|
id: "123",
|
|
email: "test@example.com",
|
|
username: "testuser",
|
|
permissions: ["space.demo.settings.delete"],
|
|
},
|
|
});
|
|
|
|
store.logout();
|
|
|
|
expect(store.isAuthenticated).toBe(false);
|
|
expect(store.user).toBeNull();
|
|
expect(apiClient.post).toHaveBeenCalledWith("/api/v1/auth/logout");
|
|
});
|
|
|
|
it("should evaluate space permissions using the space permission key", () => {
|
|
const store = useAuthStore();
|
|
store.setSession({
|
|
user: {
|
|
id: "123",
|
|
email: "test@example.com",
|
|
username: "testuser",
|
|
permissions: ["space.docs.settings.delete", "space.*.note.create"],
|
|
},
|
|
});
|
|
|
|
expect(store.hasSpacePermission({ permission_key: "docs" }, "settings.delete")).toBe(true);
|
|
expect(store.hasSpacePermission({ permission_key: "docs" }, "note.create")).toBe(true);
|
|
expect(store.hasSpacePermission({ permission_key: "docs" }, "note.delete")).toBe(false);
|
|
});
|
|
});
|