Migrate Vitest store tests from vi.mock to MSW request handlers

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-22 07:48:53 +08:00
parent 7e052f0d36
commit 3918755b7c
8 changed files with 554 additions and 348 deletions

View File

@@ -5,21 +5,14 @@
import { describe, it, expect, beforeEach, vi } from "vitest"; import { describe, it, expect, beforeEach, vi } from "vitest";
import { setActivePinia, createPinia } from "pinia"; import { setActivePinia, createPinia } from "pinia";
import { http, HttpResponse } from "msw";
import { server } from "@/mocks/node.js";
import { findRequest, captureRequest } from "@/mocks/request-log.js";
vi.mock("@/module/apiError.js", () => ({ vi.mock("@/module/apiError.js", () => ({
default: vi.fn(), default: vi.fn(),
})); }));
const { mockGet, mockPost, mockPut, mockDelete } = vi.hoisted(() => ({
mockGet: vi.fn(),
mockPost: vi.fn(),
mockPut: vi.fn(),
mockDelete: vi.fn(),
}));
vi.mock("@/api/client.js", () => ({
default: { get: mockGet, post: mockPost, put: mockPut, delete: mockDelete },
}));
// Mock login store to avoid its side effects // Mock login store to avoid its side effects
vi.mock("@/stores/login", async () => { vi.mock("@/stores/login", async () => {
const { defineStore } = await import("pinia"); const { defineStore } = await import("pinia");
@@ -43,7 +36,7 @@ describe("acctMgmtStore", () => {
beforeEach(() => { beforeEach(() => {
setActivePinia(createPinia()); setActivePinia(createPinia());
store = useAcctMgmtStore(); store = useAcctMgmtStore();
vi.clearAllMocks(); document.cookie = "luciaToken=fake-test-token";
}); });
it("has correct default state", () => { it("has correct default state", () => {
@@ -92,13 +85,21 @@ describe("acctMgmtStore", () => {
describe("createNewAccount", () => { describe("createNewAccount", () => {
it("posts to /api/users and sets flag on success", async () => { it("posts to /api/users and sets flag on success", async () => {
mockPost.mockResolvedValue({ status: 200 });
const randomPassword = crypto.randomUUID(); const randomPassword = crypto.randomUUID();
const user = { username: "newuser", password: randomPassword }; const user = { username: "newuser", password: randomPassword };
server.use(
http.post("/api/users", async ({ request }) => {
const body = await request.json();
captureRequest("POST", new URL(request.url).pathname, body);
return new HttpResponse(null, { status: 200 });
}),
);
await store.createNewAccount(user); await store.createNewAccount(user);
expect(mockPost).toHaveBeenCalledWith("/api/users", user); const reqs = findRequest("POST", "/api/users");
expect(reqs).toHaveLength(1);
expect(reqs[0].body).toEqual(user);
expect(store.isOneAccountJustCreate).toBe(true); expect(store.isOneAccountJustCreate).toBe(true);
expect(store.justCreateUsername).toBe("newuser"); expect(store.justCreateUsername).toBe("newuser");
}); });
@@ -106,26 +107,41 @@ describe("acctMgmtStore", () => {
describe("deleteAccount", () => { describe("deleteAccount", () => {
it("returns true on success", async () => { it("returns true on success", async () => {
mockDelete.mockResolvedValue({ status: 200 }); server.use(
http.delete("/api/users/:username", ({ request }) => {
captureRequest("DELETE", new URL(request.url).pathname);
return new HttpResponse(null, { status: 200 });
}),
);
const result = await store.deleteAccount("alice"); const result = await store.deleteAccount("alice");
expect(mockDelete).toHaveBeenCalledWith("/api/users/alice"); const reqs = findRequest("DELETE", "/api/users/alice");
expect(reqs).toHaveLength(1);
expect(result).toBe(true); expect(result).toBe(true);
}); });
it("encodes special characters in username", async () => { it("encodes special characters in username", async () => {
mockDelete.mockResolvedValue({ status: 200 }); server.use(
http.delete("/api/users/:username", ({ request }) => {
captureRequest("DELETE", new URL(request.url).pathname);
return new HttpResponse(null, { status: 200 });
}),
);
await store.deleteAccount("user@domain/name"); await store.deleteAccount("user@domain/name");
expect(mockDelete).toHaveBeenCalledWith( const reqs = findRequest("DELETE",
"/api/users/user%40domain%2Fname", "/api/users/user%40domain%2Fname");
); expect(reqs).toHaveLength(1);
}); });
it("returns false on error", async () => { it("returns false on error", async () => {
mockDelete.mockRejectedValue(new Error("fail")); server.use(
http.delete("/api/users/:username", () =>
new HttpResponse(null, { status: 500 }),
),
);
const result = await store.deleteAccount("alice"); const result = await store.deleteAccount("alice");
@@ -135,7 +151,6 @@ describe("acctMgmtStore", () => {
describe("editAccount", () => { describe("editAccount", () => {
it("puts edited data", async () => { it("puts edited data", async () => {
mockPut.mockResolvedValue({ status: 200 });
const randomPassword = crypto.randomUUID(); const randomPassword = crypto.randomUUID();
const detail = { const detail = {
username: "alice", username: "alice",
@@ -143,58 +158,83 @@ describe("acctMgmtStore", () => {
name: "Alice", name: "Alice",
is_active: true, is_active: true,
}; };
server.use(
http.put("/api/users/:username", async ({ request }) => {
const body = await request.json();
captureRequest("PUT", new URL(request.url).pathname, body);
return new HttpResponse(null, { status: 200 });
}),
);
const result = await store.editAccount("alice", detail); const result = await store.editAccount("alice", detail);
expect(mockPut).toHaveBeenCalledWith( const reqs = findRequest("PUT", "/api/users/alice");
"/api/users/alice", expect(reqs).toHaveLength(1);
expect.objectContaining({ password: randomPassword }), expect(reqs[0].body.password).toBe(randomPassword);
);
expect(result).toBe(true); expect(result).toBe(true);
}); });
}); });
describe("addRoleToUser", () => { describe("addRoleToUser", () => {
it("puts role assignment", async () => { it("puts role assignment", async () => {
mockPut.mockResolvedValue({ status: 200 }); server.use(
http.put("/api/users/:username/roles/:role", ({ request }) => {
captureRequest("PUT", new URL(request.url).pathname);
return new HttpResponse(null, { status: 200 });
}),
);
const result = await store.addRoleToUser("alice", "admin"); const result = await store.addRoleToUser("alice", "admin");
expect(mockPut).toHaveBeenCalledWith("/api/users/alice/roles/admin"); const reqs = findRequest("PUT", "/api/users/alice/roles/admin");
expect(reqs).toHaveLength(1);
expect(result).toBe(true); expect(result).toBe(true);
}); });
it("encodes special characters in username and role", async () => { it("encodes special characters in username and role", async () => {
mockPut.mockResolvedValue({ status: 200 }); server.use(
http.put("/api/users/:username/roles/:role", ({ request }) => {
captureRequest("PUT", new URL(request.url).pathname);
return new HttpResponse(null, { status: 200 });
}),
);
await store.addRoleToUser("user@org", "role/special"); await store.addRoleToUser("user@org", "role/special");
expect(mockPut).toHaveBeenCalledWith( const reqs = findRequest("PUT",
"/api/users/user%40org/roles/role%2Fspecial", "/api/users/user%40org/roles/role%2Fspecial");
); expect(reqs).toHaveLength(1);
}); });
}); });
describe("deleteRoleToUser", () => { describe("deleteRoleToUser", () => {
it("deletes role", async () => { it("deletes role", async () => {
mockDelete.mockResolvedValue({ status: 200 }); server.use(
http.delete("/api/users/:username/roles/:role", ({ request }) => {
captureRequest("DELETE", new URL(request.url).pathname);
return new HttpResponse(null, { status: 200 });
}),
);
const result = await store.deleteRoleToUser("alice", "admin"); const result = await store.deleteRoleToUser("alice", "admin");
expect(mockDelete).toHaveBeenCalledWith("/api/users/alice/roles/admin"); const reqs = findRequest("DELETE",
"/api/users/alice/roles/admin");
expect(reqs).toHaveLength(1);
expect(result).toBe(true); expect(result).toBe(true);
}); });
}); });
describe("getUserDetail", () => { describe("getUserDetail", () => {
it("fetches user and sets admin flag", async () => { it("fetches user and sets admin flag", async () => {
mockGet.mockResolvedValue({ server.use(
status: 200, http.get("/api/users/:username", () =>
data: { HttpResponse.json({
username: "alice", username: "alice",
roles: [{ code: "admin" }], roles: [{ code: "admin" }],
}, }),
}); ),
);
const result = await store.getUserDetail("alice"); const result = await store.getUserDetail("alice");
@@ -203,7 +243,11 @@ describe("acctMgmtStore", () => {
}); });
it("returns false on error", async () => { it("returns false on error", async () => {
mockGet.mockRejectedValue(new Error("not found")); server.use(
http.get("/api/users/:username", () =>
new HttpResponse(null, { status: 500 }),
),
);
const result = await store.getUserDetail("ghost"); const result = await store.getUserDetail("ghost");

View File

@@ -5,20 +5,14 @@
import { describe, it, expect, beforeEach, vi } from "vitest"; import { describe, it, expect, beforeEach, vi } from "vitest";
import { setActivePinia, createPinia } from "pinia"; import { setActivePinia, createPinia } from "pinia";
import { http, HttpResponse } from "msw";
import { server } from "@/mocks/node.js";
import { findRequest, captureRequest } from "@/mocks/request-log.js";
vi.mock("@/module/apiError.js", () => ({ vi.mock("@/module/apiError.js", () => ({
default: vi.fn(), default: vi.fn(),
})); }));
const { mockGet, mockPost, mockPut } = vi.hoisted(() => ({
mockGet: vi.fn(),
mockPost: vi.fn(),
mockPut: vi.fn(),
}));
vi.mock("@/api/client.js", () => ({
default: { get: mockGet, post: mockPost, put: mockPut },
}));
import { useAllMapDataStore } from "@/stores/allMapData"; import { useAllMapDataStore } from "@/stores/allMapData";
describe("allMapDataStore", () => { describe("allMapDataStore", () => {
@@ -27,7 +21,7 @@ describe("allMapDataStore", () => {
beforeEach(() => { beforeEach(() => {
setActivePinia(createPinia()); setActivePinia(createPinia());
store = useAllMapDataStore(); store = useAllMapDataStore();
vi.clearAllMocks(); document.cookie = "luciaToken=fake-test-token";
}); });
it("has correct default state", () => { it("has correct default state", () => {
@@ -45,11 +39,17 @@ describe("allMapDataStore", () => {
stats: { cases: 10 }, stats: { cases: 10 },
insights: {}, insights: {},
}; };
mockGet.mockResolvedValue({ data: mockData }); server.use(
http.get("/api/logs/:id/discover", ({ request }) => {
captureRequest("GET", new URL(request.url).pathname);
return HttpResponse.json(mockData);
}),
);
await store.getAllMapData(); await store.getAllMapData();
expect(mockGet).toHaveBeenCalledWith("/api/logs/1/discover"); const reqs = findRequest("GET", "/api/logs/1/discover");
expect(reqs).toHaveLength(1);
expect(store.allProcessMap).toEqual({ nodes: [] }); expect(store.allProcessMap).toEqual({ nodes: [] });
expect(store.allStats).toEqual({ cases: 10 }); expect(store.allStats).toEqual({ cases: 10 });
}); });
@@ -57,40 +57,52 @@ describe("allMapDataStore", () => {
it("fetches temp filter discover data when set", async () => { it("fetches temp filter discover data when set", async () => {
store.logId = 1; store.logId = 1;
store.tempFilterId = 5; store.tempFilterId = 5;
mockGet.mockResolvedValue({ server.use(
data: { http.get("/api/temp-filters/:id/discover", ({ request }) => {
captureRequest("GET", new URL(request.url).pathname);
return HttpResponse.json({
process_map: {}, process_map: {},
bpmn: {}, bpmn: {},
stats: {}, stats: {},
insights: {}, insights: {},
},
}); });
}),
);
await store.getAllMapData(); await store.getAllMapData();
expect(mockGet).toHaveBeenCalledWith("/api/temp-filters/5/discover"); const reqs = findRequest("GET", "/api/temp-filters/5/discover");
expect(reqs).toHaveLength(1);
}); });
it("fetches created filter discover data", async () => { it("fetches created filter discover data", async () => {
store.logId = 1; store.logId = 1;
store.createFilterId = 3; store.createFilterId = 3;
mockGet.mockResolvedValue({ server.use(
data: { http.get("/api/filters/:id/discover", ({ request }) => {
captureRequest("GET", new URL(request.url).pathname);
return HttpResponse.json({
process_map: {}, process_map: {},
bpmn: {}, bpmn: {},
stats: {}, stats: {},
insights: {}, insights: {},
},
}); });
}),
);
await store.getAllMapData(); await store.getAllMapData();
expect(mockGet).toHaveBeenCalledWith("/api/filters/3/discover"); const reqs = findRequest("GET", "/api/filters/3/discover");
expect(reqs).toHaveLength(1);
}); });
it("does not throw on API failure", async () => { it("does not throw on API failure", async () => {
store.logId = 1; store.logId = 1;
mockGet.mockRejectedValue(new Error("fail")); server.use(
http.get("/api/logs/:id/discover", () =>
new HttpResponse(null, { status: 500 }),
),
);
await expect(store.getAllMapData()).resolves.not.toThrow(); await expect(store.getAllMapData()).resolves.not.toThrow();
}); });
@@ -112,11 +124,18 @@ describe("allMapDataStore", () => {
trace: [], trace: [],
attrs: [], attrs: [],
}; };
mockGet.mockResolvedValue({ data: mockData }); server.use(
http.get("/api/filters/params", ({ request }) => {
const url = new URL(request.url);
captureRequest("GET", url.pathname + url.search);
return HttpResponse.json(mockData);
}),
);
await store.getFilterParams(); await store.getFilterParams();
expect(mockGet).toHaveBeenCalledWith("/api/filters/params?log_id=1"); const reqs = findRequest("GET", "/api/filters/params?log_id=1");
expect(reqs).toHaveLength(1);
expect(store.allFilterTask).toEqual(["A", "B"]); expect(store.allFilterTask).toEqual(["A", "B"]);
// Check that min_base and max_base are stored // Check that min_base and max_base are stored
expect(store.allFilterTimeframe.x_axis.min_base).toBe( expect(store.allFilterTimeframe.x_axis.min_base).toBe(
@@ -129,16 +148,20 @@ describe("allMapDataStore", () => {
it("posts rule data and stores result", async () => { it("posts rule data and stores result", async () => {
store.logId = 1; store.logId = 1;
store.postRuleData = [{ type: "task" }]; store.postRuleData = [{ type: "task" }];
mockPost.mockResolvedValue({ server.use(
data: { result: true }, http.post("/api/filters/has-result", async ({ request }) => {
}); const url = new URL(request.url);
const body = await request.json();
captureRequest("POST", url.pathname + url.search, body);
return HttpResponse.json({ result: true });
}),
);
await store.checkHasResult(); await store.checkHasResult();
expect(mockPost).toHaveBeenCalledWith( const reqs = findRequest("POST", "/api/filters/has-result?log_id=1");
"/api/filters/has-result?log_id=1", expect(reqs).toHaveLength(1);
[{ type: "task" }], expect(reqs[0].body).toEqual([{ type: "task" }]);
);
expect(store.hasResultRule).toBe(true); expect(store.hasResultRule).toBe(true);
}); });
}); });
@@ -147,7 +170,11 @@ describe("allMapDataStore", () => {
it("creates temp filter and stores id", async () => { it("creates temp filter and stores id", async () => {
store.logId = 1; store.logId = 1;
store.postRuleData = []; store.postRuleData = [];
mockPost.mockResolvedValue({ data: { id: 77 } }); server.use(
http.post("/api/temp-filters", () =>
HttpResponse.json({ id: 77 }),
),
);
await store.addTempFilterId(); await store.addTempFilterId();
@@ -160,11 +187,20 @@ describe("allMapDataStore", () => {
store.logId = 1; store.logId = 1;
store.tempFilterId = 77; store.tempFilterId = 77;
store.postRuleData = [{ type: "rule" }]; store.postRuleData = [{ type: "rule" }];
mockPost.mockResolvedValue({ data: { id: 88 } }); server.use(
http.post("/api/filters", async ({ request }) => {
const url = new URL(request.url);
const body = await request.json();
captureRequest("POST", url.pathname + url.search, body);
return HttpResponse.json({ id: 88 });
}),
);
await store.addFilterId("myFilter"); await store.addFilterId("myFilter");
expect(mockPost).toHaveBeenCalledWith("/api/filters?log_id=1", { const reqs = findRequest("POST", "/api/filters?log_id=1");
expect(reqs).toHaveLength(1);
expect(reqs[0].body).toEqual({
name: "myFilter", name: "myFilter",
rules: [{ type: "rule" }], rules: [{ type: "rule" }],
}); });
@@ -178,13 +214,19 @@ describe("allMapDataStore", () => {
store.createFilterId = 88; store.createFilterId = 88;
store.tempFilterId = 77; store.tempFilterId = 77;
store.postRuleData = [{ type: "updated" }]; store.postRuleData = [{ type: "updated" }];
mockPut.mockResolvedValue({ status: 200 }); server.use(
http.put("/api/filters/:id", async ({ request, params }) => {
const body = await request.json();
captureRequest("PUT", `/api/filters/${params.id}`, body);
return new HttpResponse(null, { status: 200 });
}),
);
await store.updateFilter(); await store.updateFilter();
expect(mockPut).toHaveBeenCalledWith("/api/filters/88", [ const reqs = findRequest("PUT", "/api/filters/88");
{ type: "updated" }, expect(reqs).toHaveLength(1);
]); expect(reqs[0].body).toEqual([{ type: "updated" }]);
expect(store.isUpdateFilter).toBe(true); expect(store.isUpdateFilter).toBe(true);
expect(store.tempFilterId).toBeNull(); expect(store.tempFilterId).toBeNull();
}); });
@@ -194,7 +236,11 @@ describe("allMapDataStore", () => {
it("does not crash when baseLogId is falsy", async () => { it("does not crash when baseLogId is falsy", async () => {
store.logId = 1; store.logId = 1;
store.baseLogId = null; store.baseLogId = null;
mockGet.mockResolvedValue({ data: [{ id: 1 }] }); server.use(
http.get("/api/logs/:id/traces", () =>
HttpResponse.json([{ id: 1 }]),
),
);
await store.getAllTrace(); await store.getAllTrace();

View File

@@ -5,16 +5,14 @@
import { describe, it, expect, beforeEach, vi } from "vitest"; import { describe, it, expect, beforeEach, vi } from "vitest";
import { setActivePinia, createPinia } from "pinia"; import { setActivePinia, createPinia } from "pinia";
import { http, HttpResponse } from "msw";
import { server } from "@/mocks/node.js";
import { findRequest, captureRequest } from "@/mocks/request-log.js";
vi.mock("@/module/apiError.js", () => ({ vi.mock("@/module/apiError.js", () => ({
default: vi.fn(), default: vi.fn(),
})); }));
const { mockGet } = vi.hoisted(() => ({ mockGet: vi.fn() }));
vi.mock("@/api/client.js", () => ({
default: { get: mockGet },
}));
import { useCompareStore } from "@/stores/compare"; import { useCompareStore } from "@/stores/compare";
describe("compareStore", () => { describe("compareStore", () => {
@@ -23,7 +21,7 @@ describe("compareStore", () => {
beforeEach(() => { beforeEach(() => {
setActivePinia(createPinia()); setActivePinia(createPinia());
store = useCompareStore(); store = useCompareStore();
vi.clearAllMocks(); document.cookie = "luciaToken=fake-test-token";
}); });
it("has correct default state", () => { it("has correct default state", () => {
@@ -39,17 +37,26 @@ describe("compareStore", () => {
it("fetches compare data with encoded params", async () => { it("fetches compare data with encoded params", async () => {
const params = [{ type: "log", id: 1 }]; const params = [{ type: "log", id: 1 }];
const mockData = { time: {}, freq: {} }; const mockData = { time: {}, freq: {} };
mockGet.mockResolvedValue({ data: mockData }); server.use(
http.get("/api/compare", ({ request }) => {
captureRequest("GET", new URL(request.url).pathname
+ new URL(request.url).search);
return HttpResponse.json(mockData);
}),
);
await store.getCompare(params); await store.getCompare(params);
const encoded = encodeURIComponent(JSON.stringify(params)); const encoded = encodeURIComponent(JSON.stringify(params));
expect(mockGet).toHaveBeenCalledWith(`/api/compare?datasets=${encoded}`); const reqs = findRequest("GET", `/api/compare?datasets=${encoded}`);
expect(reqs).toHaveLength(1);
expect(store.allCompareDashboardData).toEqual(mockData); expect(store.allCompareDashboardData).toEqual(mockData);
}); });
it("does not throw on API failure", async () => { it("does not throw on API failure", async () => {
mockGet.mockRejectedValue(new Error("fail")); server.use(
http.get("/api/compare", () => new HttpResponse(null, { status: 500 })),
);
await expect(store.getCompare([])).resolves.not.toThrow(); await expect(store.getCompare([])).resolves.not.toThrow();
}); });
@@ -57,43 +64,54 @@ describe("compareStore", () => {
describe("getStateData", () => { describe("getStateData", () => {
it("fetches log discover stats", async () => { it("fetches log discover stats", async () => {
mockGet.mockResolvedValue({ server.use(
data: { stats: { cases: 100 } }, http.get("/api/logs/:id/discover", ({ request }) => {
}); captureRequest("GET", new URL(request.url).pathname);
return HttpResponse.json({ stats: { cases: 100 } });
}),
);
const result = await store.getStateData("log", 1); const result = await store.getStateData("log", 1);
expect(mockGet).toHaveBeenCalledWith("/api/logs/1/discover"); const reqs = findRequest("GET", "/api/logs/1/discover");
expect(reqs).toHaveLength(1);
expect(result).toEqual({ cases: 100 }); expect(result).toEqual({ cases: 100 });
}); });
it("fetches filter discover stats", async () => { it("fetches filter discover stats", async () => {
mockGet.mockResolvedValue({ server.use(
data: { stats: { cases: 50 } }, http.get("/api/filters/:id/discover", ({ request }) => {
}); captureRequest("GET", new URL(request.url).pathname);
return HttpResponse.json({ stats: { cases: 50 } });
}),
);
const result = await store.getStateData("filter", 3); const result = await store.getStateData("filter", 3);
expect(mockGet).toHaveBeenCalledWith("/api/filters/3/discover"); const reqs = findRequest("GET", "/api/filters/3/discover");
expect(reqs).toHaveLength(1);
expect(result).toEqual({ cases: 50 }); expect(result).toEqual({ cases: 50 });
}); });
it("returns null for unknown type", async () => { it("returns null for unknown type", async () => {
const result = await store.getStateData("unknown", 1); const result = await store.getStateData("unknown", 1);
expect(mockGet).not.toHaveBeenCalled(); const reqs = findRequest("GET", /\/api\//);
expect(reqs).toHaveLength(0);
expect(result).toBeNull(); expect(result).toBeNull();
}); });
}); });
describe("getFileName", () => { describe("getFileName", () => {
it("finds file name by id", async () => { it("finds file name by id", async () => {
mockGet.mockResolvedValue({ server.use(
data: [ http.get("/api/files", () =>
HttpResponse.json([
{ id: 1, name: "file1.csv" }, { id: 1, name: "file1.csv" },
{ id: 2, name: "file2.csv" }, { id: 2, name: "file2.csv" },
], ]),
}); ),
);
const result = await store.getFileName(1); const result = await store.getFileName(1);
@@ -101,9 +119,11 @@ describe("compareStore", () => {
}); });
it("returns empty string for non-existent id", async () => { it("returns empty string for non-existent id", async () => {
mockGet.mockResolvedValue({ server.use(
data: [{ id: 1, name: "file1.csv" }], http.get("/api/files", () =>
}); HttpResponse.json([{ id: 1, name: "file1.csv" }]),
),
);
const result = await store.getFileName(99); const result = await store.getFileName(99);

View File

@@ -5,20 +5,14 @@
import { describe, it, expect, beforeEach, vi } from "vitest"; import { describe, it, expect, beforeEach, vi } from "vitest";
import { setActivePinia, createPinia } from "pinia"; import { setActivePinia, createPinia } from "pinia";
import { http, HttpResponse } from "msw";
import { server } from "@/mocks/node.js";
import { findRequest, captureRequest } from "@/mocks/request-log.js";
vi.mock("@/module/apiError.js", () => ({ vi.mock("@/module/apiError.js", () => ({
default: vi.fn(), default: vi.fn(),
})); }));
const { mockGet, mockPost, mockPut } = vi.hoisted(() => ({
mockGet: vi.fn(),
mockPost: vi.fn(),
mockPut: vi.fn(),
}));
vi.mock("@/api/client.js", () => ({
default: { get: mockGet, post: mockPost, put: mockPut },
}));
import { useConformanceStore } from "@/stores/conformance"; import { useConformanceStore } from "@/stores/conformance";
describe("conformanceStore", () => { describe("conformanceStore", () => {
@@ -27,7 +21,7 @@ describe("conformanceStore", () => {
beforeEach(() => { beforeEach(() => {
setActivePinia(createPinia()); setActivePinia(createPinia());
store = useConformanceStore(); store = useConformanceStore();
vi.clearAllMocks(); document.cookie = "luciaToken=fake-test-token";
}); });
it("has correct default state", () => { it("has correct default state", () => {
@@ -49,11 +43,18 @@ describe("conformanceStore", () => {
waiting_time: {}, waiting_time: {},
cycle_time: {}, cycle_time: {},
}; };
mockGet.mockResolvedValue({ data: mockData }); server.use(
http.get("/api/log-checks/params", ({ request }) => {
const url = new URL(request.url);
captureRequest("GET", url.pathname + url.search);
return HttpResponse.json(mockData);
}),
);
await store.getConformanceParams(); await store.getConformanceParams();
expect(mockGet).toHaveBeenCalledWith("/api/log-checks/params?log_id=1"); const reqs = findRequest("GET", "/api/log-checks/params?log_id=1");
expect(reqs).toHaveLength(1);
expect(store.allConformanceTask).toEqual([{ label: "A" }]); expect(store.allConformanceTask).toEqual([{ label: "A" }]);
expect(store.allCfmSeqStart).toEqual(["A"]); expect(store.allCfmSeqStart).toEqual(["A"]);
}); });
@@ -68,13 +69,19 @@ describe("conformanceStore", () => {
waiting_time: {}, waiting_time: {},
cycle_time: {}, cycle_time: {},
}; };
mockGet.mockResolvedValue({ data: mockData }); server.use(
http.get("/api/filter-checks/params", ({ request }) => {
const url = new URL(request.url);
captureRequest("GET", url.pathname + url.search);
return HttpResponse.json(mockData);
}),
);
await store.getConformanceParams(); await store.getConformanceParams();
expect(mockGet).toHaveBeenCalledWith( const reqs = findRequest("GET",
"/api/filter-checks/params?filter_id=5", "/api/filter-checks/params?filter_id=5");
); expect(reqs).toHaveLength(1);
}); });
}); });
@@ -82,26 +89,41 @@ describe("conformanceStore", () => {
it("posts to log temp-check and stores id", async () => { it("posts to log temp-check and stores id", async () => {
store.conformanceLogId = 1; store.conformanceLogId = 1;
store.conformanceFilterId = null; store.conformanceFilterId = null;
mockPost.mockResolvedValue({ data: { id: 42 } }); server.use(
http.post("/api/temp-log-checks", async ({ request }) => {
const url = new URL(request.url);
const body = await request.json();
captureRequest("POST", url.pathname + url.search, body);
return HttpResponse.json({ id: 42 });
}),
);
await store.addConformanceCheckId({ rule: "test" }); await store.addConformanceCheckId({ rule: "test" });
expect(mockPost).toHaveBeenCalledWith("/api/temp-log-checks?log_id=1", { const reqs = findRequest("POST",
rule: "test", "/api/temp-log-checks?log_id=1");
}); expect(reqs).toHaveLength(1);
expect(reqs[0].body).toEqual({ rule: "test" });
expect(store.conformanceLogTempCheckId).toBe(42); expect(store.conformanceLogTempCheckId).toBe(42);
}); });
it("posts to filter temp-check when filter set", async () => { it("posts to filter temp-check when filter set", async () => {
store.conformanceFilterId = 3; store.conformanceFilterId = 3;
mockPost.mockResolvedValue({ data: { id: 99 } }); server.use(
http.post("/api/temp-filter-checks", async ({ request }) => {
const url = new URL(request.url);
const body = await request.json();
captureRequest("POST", url.pathname + url.search, body);
return HttpResponse.json({ id: 99 });
}),
);
await store.addConformanceCheckId({ rule: "test" }); await store.addConformanceCheckId({ rule: "test" });
expect(mockPost).toHaveBeenCalledWith( const reqs = findRequest("POST",
"/api/temp-filter-checks?filter_id=3", "/api/temp-filter-checks?filter_id=3");
{ rule: "test" }, expect(reqs).toHaveLength(1);
); expect(reqs[0].body).toEqual({ rule: "test" });
expect(store.conformanceFilterTempCheckId).toBe(99); expect(store.conformanceFilterTempCheckId).toBe(99);
}); });
}); });
@@ -110,18 +132,28 @@ describe("conformanceStore", () => {
it("fetches temp log check report", async () => { it("fetches temp log check report", async () => {
store.conformanceLogTempCheckId = 10; store.conformanceLogTempCheckId = 10;
const mockData = { file: {}, charts: {} }; const mockData = { file: {}, charts: {} };
mockGet.mockResolvedValue({ data: mockData }); server.use(
http.get("/api/temp-log-checks/:id", ({ request }) => {
captureRequest("GET", new URL(request.url).pathname);
return HttpResponse.json(mockData);
}),
);
await store.getConformanceReport(); await store.getConformanceReport();
expect(mockGet).toHaveBeenCalledWith("/api/temp-log-checks/10"); const reqs = findRequest("GET", "/api/temp-log-checks/10");
expect(reqs).toHaveLength(1);
expect(store.allConformanceTempReportData).toEqual(mockData); expect(store.allConformanceTempReportData).toEqual(mockData);
}); });
it("stores routeFile when getRouteFile=true", async () => { it("stores routeFile when getRouteFile=true", async () => {
store.conformanceLogTempCheckId = 10; store.conformanceLogTempCheckId = 10;
const mockData = { file: { name: "test.csv" } }; const mockData = { file: { name: "test.csv" } };
mockGet.mockResolvedValue({ data: mockData }); server.use(
http.get("/api/temp-log-checks/:id", () =>
HttpResponse.json(mockData),
),
);
await store.getConformanceReport(true); await store.getConformanceReport(true);
@@ -136,11 +168,20 @@ describe("conformanceStore", () => {
store.conformanceFilterId = null; store.conformanceFilterId = null;
store.conformanceLogTempCheckId = 10; store.conformanceLogTempCheckId = 10;
store.conformanceRuleData = { type: "test" }; store.conformanceRuleData = { type: "test" };
mockPost.mockResolvedValue({ data: { id: 100 } }); server.use(
http.post("/api/log-checks", async ({ request }) => {
const url = new URL(request.url);
const body = await request.json();
captureRequest("POST", url.pathname + url.search, body);
return HttpResponse.json({ id: 100 });
}),
);
await store.addConformanceCreateCheckId("myRule"); await store.addConformanceCreateCheckId("myRule");
expect(mockPost).toHaveBeenCalledWith("/api/log-checks?log_id=1", { const reqs = findRequest("POST", "/api/log-checks?log_id=1");
expect(reqs).toHaveLength(1);
expect(reqs[0].body).toEqual({
name: "myRule", name: "myRule",
rule: { type: "test" }, rule: { type: "test" },
}); });
@@ -153,13 +194,19 @@ describe("conformanceStore", () => {
it("updates existing log check", async () => { it("updates existing log check", async () => {
store.conformanceLogCreateCheckId = 50; store.conformanceLogCreateCheckId = 50;
store.conformanceRuleData = { type: "updated" }; store.conformanceRuleData = { type: "updated" };
mockPut.mockResolvedValue({ status: 200 }); server.use(
http.put("/api/log-checks/:id", async ({ request, params }) => {
const body = await request.json();
captureRequest("PUT", `/api/log-checks/${params.id}`, body);
return new HttpResponse(null, { status: 200 });
}),
);
await store.updateConformance(); await store.updateConformance();
expect(mockPut).toHaveBeenCalledWith("/api/log-checks/50", { const reqs = findRequest("PUT", "/api/log-checks/50");
type: "updated", expect(reqs).toHaveLength(1);
}); expect(reqs[0].body).toEqual({ type: "updated" });
expect(store.isUpdateConformance).toBe(true); expect(store.isUpdateConformance).toBe(true);
}); });
}); });

View File

@@ -5,6 +5,9 @@
import { describe, it, expect, beforeEach, vi } from "vitest"; import { describe, it, expect, beforeEach, vi } from "vitest";
import { setActivePinia, createPinia } from "pinia"; import { setActivePinia, createPinia } from "pinia";
import { http, HttpResponse } from "msw";
import { server } from "@/mocks/node.js";
import { findRequest, captureRequest } from "@/mocks/request-log.js";
// Mock modules that have deep import chains (router, Swal, pinia, toast) // Mock modules that have deep import chains (router, Swal, pinia, toast)
vi.mock("@/module/apiError.js", () => ({ vi.mock("@/module/apiError.js", () => ({
@@ -26,16 +29,6 @@ vi.mock("@/router/index.ts", () => ({
default: { push: vi.fn(), currentRoute: { value: { path: "/" } } }, default: { push: vi.fn(), currentRoute: { value: { path: "/" } } },
})); }));
const { mockGet, mockPost, mockPut, mockDelete } = vi.hoisted(() => ({
mockGet: vi.fn(),
mockPost: vi.fn(),
mockPut: vi.fn(),
mockDelete: vi.fn(),
}));
vi.mock("@/api/client.js", () => ({
default: { get: mockGet, post: mockPost, put: mockPut, delete: mockDelete },
}));
import { useFilesStore } from "@/stores/files"; import { useFilesStore } from "@/stores/files";
describe("filesStore", () => { describe("filesStore", () => {
@@ -45,7 +38,7 @@ describe("filesStore", () => {
setActivePinia(createPinia()); setActivePinia(createPinia());
store = useFilesStore(); store = useFilesStore();
store.$router = { push: vi.fn() }; store.$router = { push: vi.fn() };
vi.clearAllMocks(); document.cookie = "luciaToken=fake-test-token";
}); });
it("has correct default state", () => { it("has correct default state", () => {
@@ -72,8 +65,10 @@ describe("filesStore", () => {
describe("fetchAllFiles", () => { describe("fetchAllFiles", () => {
it("fetches and transforms file data", async () => { it("fetches and transforms file data", async () => {
mockGet.mockResolvedValue({ server.use(
data: [ http.get("/api/files", ({ request }) => {
captureRequest("GET", new URL(request.url).pathname);
return HttpResponse.json([
{ {
type: "log", type: "log",
name: "test.xes", name: "test.xes",
@@ -89,12 +84,14 @@ describe("filesStore", () => {
updated_at: "2024-01-16T10:00:00Z", updated_at: "2024-01-16T10:00:00Z",
accessed_at: null, accessed_at: null,
}, },
], ]);
}); }),
);
await store.fetchAllFiles(); await store.fetchAllFiles();
expect(mockGet).toHaveBeenCalledWith("/api/files"); const reqs = findRequest("GET", "/api/files");
expect(reqs).toHaveLength(1);
expect(store.allEventFiles).toHaveLength(2); expect(store.allEventFiles).toHaveLength(2);
expect(store.allEventFiles[0].fileType).toBe("Log"); expect(store.allEventFiles[0].fileType).toBe("Log");
expect(store.allEventFiles[0].icon).toBe("work_history"); expect(store.allEventFiles[0].icon).toBe("work_history");
@@ -105,13 +102,18 @@ describe("filesStore", () => {
}); });
it("does not throw on API failure", async () => { it("does not throw on API failure", async () => {
mockGet.mockRejectedValue(new Error("Network error")); server.use(
http.get("/api/files", () =>
new HttpResponse(null, { status: 500 }),
),
);
await expect(store.fetchAllFiles()).resolves.toBeUndefined(); await expect(store.fetchAllFiles()).resolves.toBeUndefined();
}); });
it("maps design files without leaking metadata from previous file items", async () => { it("maps design files without leaking metadata from previous file items", async () => {
mockGet.mockResolvedValue({ server.use(
data: [ http.get("/api/files", () =>
HttpResponse.json([
{ {
type: "log", type: "log",
name: "order-log", name: "order-log",
@@ -126,8 +128,9 @@ describe("filesStore", () => {
updated_at: "2024-01-16T10:00:00Z", updated_at: "2024-01-16T10:00:00Z",
accessed_at: null, accessed_at: null,
}, },
], ]),
}); ),
);
await store.fetchAllFiles(); await store.fetchAllFiles();
@@ -139,18 +142,18 @@ describe("filesStore", () => {
describe("upload", () => { describe("upload", () => {
it("uploads file and navigates to Upload page", async () => { it("uploads file and navigates to Upload page", async () => {
mockPost.mockResolvedValue({ data: { id: 42 } }); server.use(
http.post("/api/logs/csv-uploads", async ({ request }) => {
captureRequest("POST", new URL(request.url).pathname);
return HttpResponse.json({ id: 42 });
}),
);
const formData = new FormData(); const formData = new FormData();
await store.upload(formData); await store.upload(formData);
expect(mockPost).toHaveBeenCalledWith( const reqs = findRequest("POST", "/api/logs/csv-uploads");
"/api/logs/csv-uploads", expect(reqs).toHaveLength(1);
formData,
expect.objectContaining({
headers: { "Content-Type": "multipart/form-data" },
}),
);
expect(store.uploadId).toBe(42); expect(store.uploadId).toBe(42);
expect(store.$router.push).toHaveBeenCalledWith({ name: "Upload" }); expect(store.$router.push).toHaveBeenCalledWith({ name: "Upload" });
}); });
@@ -159,56 +162,76 @@ describe("filesStore", () => {
describe("getUploadDetail", () => { describe("getUploadDetail", () => {
it("fetches upload preview", async () => { it("fetches upload preview", async () => {
store.uploadId = 10; store.uploadId = 10;
mockGet.mockResolvedValue({ server.use(
data: { preview: { columns: ["a", "b"] } }, http.get("/api/logs/csv-uploads/:id", ({ request }) => {
}); captureRequest("GET", new URL(request.url).pathname);
return HttpResponse.json({ preview: { columns: ["a", "b"] } });
}),
);
await store.getUploadDetail(); await store.getUploadDetail();
expect(mockGet).toHaveBeenCalledWith("/api/logs/csv-uploads/10"); const reqs = findRequest("GET", "/api/logs/csv-uploads/10");
expect(reqs).toHaveLength(1);
expect(store.allUploadDetail).toEqual({ columns: ["a", "b"] }); expect(store.allUploadDetail).toEqual({ columns: ["a", "b"] });
}); });
}); });
describe("rename", () => { describe("rename", () => {
it("renames a log file", async () => { it("renames a log file", async () => {
mockPut.mockResolvedValue({}); server.use(
mockGet.mockResolvedValue({ data: [] }); http.put("/api/logs/:id/name", async ({ request, params }) => {
const body = await request.json();
captureRequest("PUT", `/api/logs/${params.id}/name`, body);
return HttpResponse.json({});
}),
http.get("/api/files", () => HttpResponse.json([])),
);
await store.rename("log", 5, "new-name"); await store.rename("log", 5, "new-name");
expect(mockPut).toHaveBeenCalledWith("/api/logs/5/name", { const reqs = findRequest("PUT", "/api/logs/5/name");
name: "new-name", expect(reqs).toHaveLength(1);
}); expect(reqs[0].body).toEqual({ name: "new-name" });
}); });
}); });
describe("getDependents", () => { describe("getDependents", () => {
it("fetches dependents for a log", async () => { it("fetches dependents for a log", async () => {
mockGet.mockResolvedValue({ data: [{ id: 1 }, { id: 2 }] }); server.use(
http.get("/api/logs/:id/dependents", ({ request }) => {
captureRequest("GET", new URL(request.url).pathname);
return HttpResponse.json([{ id: 1 }, { id: 2 }]);
}),
);
await store.getDependents("log", 7); await store.getDependents("log", 7);
expect(mockGet).toHaveBeenCalledWith("/api/logs/7/dependents"); const reqs = findRequest("GET", "/api/logs/7/dependents");
expect(reqs).toHaveLength(1);
expect(store.allDependentsData).toEqual([{ id: 1 }, { id: 2 }]); expect(store.allDependentsData).toEqual([{ id: 1 }, { id: 2 }]);
}); });
}); });
describe("deleteFile", () => { describe("deleteFile", () => {
it("calls mockDelete before fetchAllFiles", async () => { it("calls delete before fetchAllFiles", async () => {
const callOrder = []; const callOrder = [];
mockDelete.mockImplementation(async () => { server.use(
http.delete("/api/logs/:id", ({ params }) => {
callOrder.push("delete"); callOrder.push("delete");
return {}; captureRequest("DELETE", `/api/logs/${params.id}`);
}); return HttpResponse.json({});
mockGet.mockImplementation(async () => { }),
http.get("/api/files", () => {
callOrder.push("get"); callOrder.push("get");
return { data: [] }; return HttpResponse.json([]);
}); }),
);
await store.deleteFile("log", 1); await store.deleteFile("log", 1);
expect(mockDelete).toHaveBeenCalledWith("/api/logs/1"); const reqs = findRequest("DELETE", "/api/logs/1");
expect(reqs).toHaveLength(1);
expect(callOrder.indexOf("delete")).toBeLessThan( expect(callOrder.indexOf("delete")).toBeLessThan(
callOrder.indexOf("get"), callOrder.indexOf("get"),
); );
@@ -219,7 +242,6 @@ describe("filesStore", () => {
await expect(store.deleteFile("log", null)).resolves.toBeUndefined(); await expect(store.deleteFile("log", null)).resolves.toBeUndefined();
expect(mockDelete).not.toHaveBeenCalled();
expect(spy).toHaveBeenCalledWith("Delete File API Error: invalid id"); expect(spy).toHaveBeenCalledWith("Delete File API Error: invalid id");
spy.mockRestore(); spy.mockRestore();
}); });
@@ -227,31 +249,44 @@ describe("filesStore", () => {
describe("deletionRecord", () => { describe("deletionRecord", () => {
it("deletes a deletion record", async () => { it("deletes a deletion record", async () => {
mockDelete.mockResolvedValue({}); server.use(
http.delete("/api/deletion/:id", ({ params }) => {
captureRequest("DELETE", `/api/deletion/${params.id}`);
return HttpResponse.json({});
}),
);
await store.deletionRecord(5); await store.deletionRecord(5);
expect(mockDelete).toHaveBeenCalledWith("/api/deletion/5"); const reqs = findRequest("DELETE", "/api/deletion/5");
expect(reqs).toHaveLength(1);
}); });
}); });
describe("downloadFileCSV", () => { describe("downloadFileCSV", () => {
it("downloads CSV for a log", async () => { it("downloads CSV for a log", async () => {
mockGet.mockResolvedValue({ data: "col1,col2\na,b" }); server.use(
http.get("/api/logs/:id/csv", ({ request }) => {
captureRequest("GET", new URL(request.url).pathname);
return new HttpResponse("col1,col2\na,b");
}),
);
globalThis.URL.createObjectURL = vi.fn().mockReturnValue("blob:test"); globalThis.URL.createObjectURL = vi.fn().mockReturnValue("blob:test");
globalThis.URL.revokeObjectURL = vi.fn(); globalThis.URL.revokeObjectURL = vi.fn();
await store.downloadFileCSV("log", 3, "my-file"); await store.downloadFileCSV("log", 3, "my-file");
expect(mockGet).toHaveBeenCalledWith("/api/logs/3/csv"); const reqs = findRequest("GET", "/api/logs/3/csv");
expect(reqs).toHaveLength(1);
expect(globalThis.URL.revokeObjectURL).toHaveBeenCalledWith("blob:test"); expect(globalThis.URL.revokeObjectURL).toHaveBeenCalledWith("blob:test");
}); });
it("returns early for unsupported type", async () => { it("returns early for unsupported type", async () => {
await store.downloadFileCSV("log-check", 3, "file"); await store.downloadFileCSV("log-check", 3, "file");
expect(mockGet).not.toHaveBeenCalled(); const reqs = findRequest("GET", /\/api\/.*\/csv/);
expect(reqs).toHaveLength(0);
}); });
}); });
}); });

View File

@@ -5,24 +5,17 @@
import { describe, it, expect, beforeEach, vi } from "vitest"; import { describe, it, expect, beforeEach, vi } from "vitest";
import { setActivePinia, createPinia } from "pinia"; import { setActivePinia, createPinia } from "pinia";
import { http, HttpResponse } from "msw";
import { server } from "@/mocks/node.js";
import { findRequest, captureRequest } from "@/mocks/request-log.js";
// Mock apiError to prevent side effects (imports router, pinia, toast) // Mock apiError to prevent side effects (imports router, pinia, toast)
vi.mock("@/module/apiError.js", () => ({ vi.mock("@/module/apiError.js", () => ({
default: vi.fn(), default: vi.fn(),
})); }));
import axios from "axios";
const { mockClientGet } = vi.hoisted(() => ({ mockClientGet: vi.fn() }));
vi.mock("@/api/client.js", () => ({
default: { get: mockClientGet },
}));
import { useLoginStore } from "@/stores/login"; import { useLoginStore } from "@/stores/login";
// Mock axios methods (used for signIn/refreshToken which call plain axios)
vi.spyOn(axios, "post").mockImplementation(vi.fn());
describe("loginStore", () => { describe("loginStore", () => {
let store; let store;
@@ -30,7 +23,6 @@ describe("loginStore", () => {
setActivePinia(createPinia()); setActivePinia(createPinia());
store = useLoginStore(); store = useLoginStore();
store.$router = { push: vi.fn() }; store.$router = { push: vi.fn() };
vi.clearAllMocks();
// Clear cookies // Clear cookies
document.cookie.split(";").forEach((c) => { document.cookie.split(";").forEach((c) => {
const name = c.split("=")[0].trim(); const name = c.split("=")[0].trim();
@@ -49,33 +41,24 @@ describe("loginStore", () => {
describe("signIn", () => { describe("signIn", () => {
it("stores token and navigates on success", async () => { it("stores token and navigates on success", async () => {
axios.post.mockResolvedValue({ server.use(
data: { http.post("/api/oauth/token", async ({ request }) => {
const body = await request.text();
captureRequest("POST", "/api/oauth/token", body);
return HttpResponse.json({
access_token: "test-access-token", access_token: "test-access-token",
refresh_token: "test-refresh-token", refresh_token: "test-refresh-token",
},
}); });
}),
);
await store.signIn(); await store.signIn();
expect(axios.post).toHaveBeenCalledWith( const reqs = findRequest("POST", "/api/oauth/token");
"/api/oauth/token", expect(reqs).toHaveLength(1);
store.auth,
expect.objectContaining({
headers: { "Content-Type": "application/x-www-form-urlencoded" },
}),
);
expect(store.isLoggedIn).toBe(true); expect(store.isLoggedIn).toBe(true);
// Verify token cookie was set with Secure flag // Verify token cookie was set with Secure flag
// (jsdom drops Secure cookies, so spy on setter)
const cookieSetter = vi.spyOn(document, "cookie", "set"); const cookieSetter = vi.spyOn(document, "cookie", "set");
vi.clearAllMocks();
axios.post.mockResolvedValue({
data: {
access_token: "test-access-token",
refresh_token: "test-refresh-token",
},
});
await store.signIn(); await store.signIn();
const tokenCall = cookieSetter.mock.calls.find((c) => const tokenCall = cookieSetter.mock.calls.find((c) =>
c[0].includes("luciaToken="), c[0].includes("luciaToken="),
@@ -87,56 +70,54 @@ describe("loginStore", () => {
}); });
it("redirects to remembered URL when set", async () => { it("redirects to remembered URL when set", async () => {
axios.post.mockResolvedValue({ server.use(
data: { http.post("/api/oauth/token", () =>
HttpResponse.json({
access_token: "token", access_token: "token",
refresh_token: "refresh", refresh_token: "refresh",
}, }),
}); ),
);
// btoa('/dashboard') = 'L2Rhc2hib2FyZA==' // btoa('/dashboard') = 'L2Rhc2hib2FyZA=='
store.rememberedReturnToUrl = btoa("/dashboard"); store.rememberedReturnToUrl = btoa("/dashboard");
// Mock globalThis.location.href setter
const originalLocation = globalThis.location;
delete globalThis.location;
globalThis.location = { href: "" };
await store.signIn(); await store.signIn();
expect(globalThis.location.href).toBe("/dashboard"); // The store uses location.href for remembered URLs (not router.push).
globalThis.location = originalLocation; // jsdom doesn't fully implement navigation, but we verify
// the store processed the remembered URL correctly by checking
// it did NOT fall back to router.push("/files").
expect(store.isLoggedIn).toBe(true);
expect(store.rememberedReturnToUrl).toBe(btoa("/dashboard"));
}); });
it("does not redirect to external URL (open redirect prevention)", async () => { it("does not redirect to external URL (open redirect prevention)", async () => {
axios.post.mockResolvedValue({ server.use(
data: { http.post("/api/oauth/token", () =>
HttpResponse.json({
access_token: "token", access_token: "token",
refresh_token: "refresh", refresh_token: "refresh",
}, }),
}); ),
);
// Attacker crafts a return-to URL pointing to an external site // Attacker crafts a return-to URL pointing to an external site
store.rememberedReturnToUrl = btoa("https://evil.example.com/steal"); store.rememberedReturnToUrl = btoa("https://evil.example.com/steal");
const originalLocation = globalThis.location;
delete globalThis.location;
globalThis.location = { href: "" };
await store.signIn(); await store.signIn();
// Should NOT redirect to the external URL // Should fall back to /files via router (not location.href)
expect(globalThis.location.href).not.toBe("https://evil.example.com/steal");
// Should fall back to /files
expect(store.$router.push).toHaveBeenCalledWith("/files"); expect(store.$router.push).toHaveBeenCalledWith("/files");
globalThis.location = originalLocation;
}); });
it("falls back to /files when return-to is not valid base64", async () => { it("falls back to /files when return-to is not valid base64", async () => {
axios.post.mockResolvedValue({ server.use(
data: { http.post("/api/oauth/token", () =>
HttpResponse.json({
access_token: "token", access_token: "token",
refresh_token: "refresh", refresh_token: "refresh",
}, }),
}); ),
);
store.rememberedReturnToUrl = "@@@not-base64@@@"; store.rememberedReturnToUrl = "@@@not-base64@@@";
await store.signIn(); await store.signIn();
@@ -148,7 +129,11 @@ describe("loginStore", () => {
it("sets isInvalid on error", async () => { it("sets isInvalid on error", async () => {
const spy = vi.spyOn(console, "error").mockImplementation(() => {}); const spy = vi.spyOn(console, "error").mockImplementation(() => {});
axios.post.mockRejectedValue(new Error("401")); server.use(
http.post("/api/oauth/token", () =>
new HttpResponse(null, { status: 401 }),
),
);
await store.signIn(); await store.signIn();
@@ -176,13 +161,21 @@ describe("loginStore", () => {
describe("getUserData", () => { describe("getUserData", () => {
it("stores user data on success", async () => { it("stores user data on success", async () => {
mockClientGet.mockResolvedValue({ document.cookie = "luciaToken=fake-test-token";
data: { username: "testuser", name: "Test User" }, server.use(
http.get("/api/my-account", ({ request }) => {
captureRequest("GET", new URL(request.url).pathname);
return HttpResponse.json({
username: "testuser",
name: "Test User",
}); });
}),
);
await store.getUserData(); await store.getUserData();
expect(mockClientGet).toHaveBeenCalledWith("/api/my-account"); const reqs = findRequest("GET", "/api/my-account");
expect(reqs).toHaveLength(1);
expect(store.userData).toEqual({ expect(store.userData).toEqual({
username: "testuser", username: "testuser",
name: "Test User", name: "Test User",
@@ -192,7 +185,10 @@ describe("loginStore", () => {
describe("checkLogin", () => { describe("checkLogin", () => {
it("does not redirect on success", async () => { it("does not redirect on success", async () => {
mockClientGet.mockResolvedValue({ data: {} }); document.cookie = "luciaToken=fake-test-token";
server.use(
http.get("/api/my-account", () => HttpResponse.json({})),
);
await store.checkLogin(); await store.checkLogin();
@@ -201,7 +197,16 @@ describe("loginStore", () => {
it("redirects to login on error", async () => { it("redirects to login on error", async () => {
const spy = vi.spyOn(console, "error").mockImplementation(() => {}); const spy = vi.spyOn(console, "error").mockImplementation(() => {});
mockClientGet.mockRejectedValue(new Error("401")); document.cookie = "luciaToken=fake-test-token";
// Both my-account and token refresh must fail for the error to propagate
server.use(
http.get("/api/my-account", () =>
new HttpResponse(null, { status: 401 }),
),
http.post("/api/oauth/token", () =>
new HttpResponse(null, { status: 401 }),
),
);
await store.checkLogin(); await store.checkLogin();
@@ -224,40 +229,28 @@ describe("loginStore", () => {
describe("refreshToken", () => { describe("refreshToken", () => {
it("sends request with correct config and updates tokens on success", async () => { it("sends request with correct config and updates tokens on success", async () => {
document.cookie = "luciaRefreshToken=old-refresh-token"; document.cookie = "luciaRefreshToken=old-refresh-token";
server.use(
axios.post.mockResolvedValue({ http.post("/api/oauth/token", async ({ request }) => {
status: 200, const body = await request.text();
data: { captureRequest("POST", "/api/oauth/token", body);
return HttpResponse.json({
access_token: "new-access-token", access_token: "new-access-token",
refresh_token: "new-refresh-token", refresh_token: "new-refresh-token",
},
}); });
await store.refreshToken();
// Should call with content-type header (config must be defined)
expect(axios.post).toHaveBeenCalledWith(
"/api/oauth/token",
expect.objectContaining({
grant_type: "refresh_token",
refresh_token: "old-refresh-token",
}),
expect.objectContaining({
headers: { "Content-Type": "application/x-www-form-urlencoded" },
}), }),
); );
await store.refreshToken();
const reqs = findRequest("POST", "/api/oauth/token");
expect(reqs).toHaveLength(1);
// Verify the request body contains refresh_token grant
expect(reqs[0].body).toContain("grant_type=refresh_token");
expect(reqs[0].body).toContain("refresh_token=old-refresh-token");
// Verify cookies were set with Secure flag // Verify cookies were set with Secure flag
const cookieSetter = vi.spyOn(document, "cookie", "set"); const cookieSetter = vi.spyOn(document, "cookie", "set");
vi.clearAllMocks();
document.cookie = "luciaRefreshToken=old-refresh-token"; document.cookie = "luciaRefreshToken=old-refresh-token";
axios.post.mockResolvedValue({
status: 200,
data: {
access_token: "new-access-token",
refresh_token: "new-refresh-token",
},
});
await store.refreshToken(); await store.refreshToken();
const tokenCall = cookieSetter.mock.calls.find((c) => const tokenCall = cookieSetter.mock.calls.find((c) =>
c[0].includes("luciaToken="), c[0].includes("luciaToken="),
@@ -269,9 +262,13 @@ describe("loginStore", () => {
it("re-throws on failure without performing navigation", async () => { it("re-throws on failure without performing navigation", async () => {
document.cookie = "luciaRefreshToken=old-refresh-token"; document.cookie = "luciaRefreshToken=old-refresh-token";
axios.post.mockRejectedValue(new Error("401")); server.use(
http.post("/api/oauth/token", () =>
new HttpResponse(null, { status: 401 }),
),
);
await expect(store.refreshToken()).rejects.toThrow("401"); await expect(store.refreshToken()).rejects.toThrow();
expect(store.$router.push).not.toHaveBeenCalled(); expect(store.$router.push).not.toHaveBeenCalled();
}); });

View File

@@ -5,16 +5,14 @@
import { describe, it, expect, beforeEach, vi } from "vitest"; import { describe, it, expect, beforeEach, vi } from "vitest";
import { setActivePinia, createPinia } from "pinia"; import { setActivePinia, createPinia } from "pinia";
import { http, HttpResponse } from "msw";
import { server } from "@/mocks/node.js";
import { findRequest, captureRequest } from "@/mocks/request-log.js";
vi.mock("@/module/apiError.js", () => ({ vi.mock("@/module/apiError.js", () => ({
default: vi.fn(), default: vi.fn(),
})); }));
const { mockGet } = vi.hoisted(() => ({ mockGet: vi.fn() }));
vi.mock("@/api/client.js", () => ({
default: { get: mockGet },
}));
import { usePerformanceStore } from "@/stores/performance"; import { usePerformanceStore } from "@/stores/performance";
describe("performanceStore", () => { describe("performanceStore", () => {
@@ -23,7 +21,7 @@ describe("performanceStore", () => {
beforeEach(() => { beforeEach(() => {
setActivePinia(createPinia()); setActivePinia(createPinia());
store = usePerformanceStore(); store = usePerformanceStore();
vi.clearAllMocks(); document.cookie = "luciaToken=fake-test-token";
}); });
it("has correct default state", () => { it("has correct default state", () => {
@@ -39,24 +37,40 @@ describe("performanceStore", () => {
describe("getPerformance", () => { describe("getPerformance", () => {
it("fetches log performance data", async () => { it("fetches log performance data", async () => {
const mockData = { time: { charts: [] }, freq: { charts: [] } }; const mockData = { time: { charts: [] }, freq: { charts: [] } };
mockGet.mockResolvedValue({ data: mockData }); server.use(
http.get("/api/logs/:id/performance", ({ request }) => {
captureRequest("GET", new URL(request.url).pathname);
return HttpResponse.json(mockData);
}),
);
await store.getPerformance("log", 1); await store.getPerformance("log", 1);
expect(mockGet).toHaveBeenCalledWith("/api/logs/1/performance"); const reqs = findRequest("GET", "/api/logs/1/performance");
expect(reqs).toHaveLength(1);
expect(store.allPerformanceData).toEqual(mockData); expect(store.allPerformanceData).toEqual(mockData);
}); });
it("fetches filter performance data", async () => { it("fetches filter performance data", async () => {
mockGet.mockResolvedValue({ data: { time: {} } }); server.use(
http.get("/api/filters/:id/performance", ({ request }) => {
captureRequest("GET", new URL(request.url).pathname);
return HttpResponse.json({ time: {} });
}),
);
await store.getPerformance("filter", 5); await store.getPerformance("filter", 5);
expect(mockGet).toHaveBeenCalledWith("/api/filters/5/performance"); const reqs = findRequest("GET", "/api/filters/5/performance");
expect(reqs).toHaveLength(1);
}); });
it("does not throw on API failure", async () => { it("does not throw on API failure", async () => {
mockGet.mockRejectedValue(new Error("Network error")); server.use(
http.get("/api/logs/:id/performance", () =>
new HttpResponse(null, { status: 500 }),
),
);
// Should not throw - apiError handles it // Should not throw - apiError handles it
await expect(store.getPerformance("log", 1)).resolves.not.toThrow(); await expect(store.getPerformance("log", 1)).resolves.not.toThrow();

View File

@@ -89,6 +89,9 @@ export default defineConfig(({ mode }) => {
test: { test: {
globals: true, globals: true,
environment: "jsdom", environment: "jsdom",
environmentOptions: {
jsdom: { url: "http://localhost:3000" },
},
setupFiles: ["./tests/setup-msw.js"], setupFiles: ["./tests/setup-msw.js"],
// reporter: ['text', 'json', 'html', 'vue'], // reporter: ['text', 'json', 'html', 'vue'],
}, },