|
@@ -2,7 +2,6 @@
|
|
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
|
|
|
|
|
|
// 1) Mocks
|
|
// 1) Mocks
|
|
|
-
|
|
|
|
|
vi.mock("@/lib/db", () => ({
|
|
vi.mock("@/lib/db", () => ({
|
|
|
getDb: vi.fn(),
|
|
getDb: vi.fn(),
|
|
|
}));
|
|
}));
|
|
@@ -26,7 +25,6 @@ vi.mock("bcryptjs", () => {
|
|
|
});
|
|
});
|
|
|
|
|
|
|
|
// 2) Imports AFTER the mocks
|
|
// 2) Imports AFTER the mocks
|
|
|
-
|
|
|
|
|
import { getDb } from "@/lib/db";
|
|
import { getDb } from "@/lib/db";
|
|
|
import User from "@/models/user";
|
|
import User from "@/models/user";
|
|
|
import { createSession } from "@/lib/auth/session";
|
|
import { createSession } from "@/lib/auth/session";
|
|
@@ -107,6 +105,32 @@ describe("POST /api/auth/login", () => {
|
|
|
expect(createSession).not.toHaveBeenCalled();
|
|
expect(createSession).not.toHaveBeenCalled();
|
|
|
});
|
|
});
|
|
|
|
|
|
|
|
|
|
+ it("returns 401 when passwordHash is missing (defensive)", async () => {
|
|
|
|
|
+ User.findOne.mockReturnValue({
|
|
|
|
|
+ exec: vi.fn().mockResolvedValue({
|
|
|
|
|
+ _id: "507f1f77bcf86cd799439099",
|
|
|
|
|
+ username: "branchuser",
|
|
|
|
|
+ // passwordHash missing on purpose
|
|
|
|
|
+ role: "branch",
|
|
|
|
|
+ branchId: "NL01",
|
|
|
|
|
+ }),
|
|
|
|
|
+ });
|
|
|
|
|
+
|
|
|
|
|
+ const request = createRequestStub({
|
|
|
|
|
+ username: "branchuser",
|
|
|
|
|
+ password: "secret-password",
|
|
|
|
|
+ });
|
|
|
|
|
+
|
|
|
|
|
+ const response = await POST(request);
|
|
|
|
|
+ const json = await response.json();
|
|
|
|
|
+
|
|
|
|
|
+ expect(response.status).toBe(401);
|
|
|
|
|
+ expect(json).toEqual({ error: "Invalid credentials" });
|
|
|
|
|
+
|
|
|
|
|
+ expect(bcryptCompare).not.toHaveBeenCalled();
|
|
|
|
|
+ expect(createSession).not.toHaveBeenCalled();
|
|
|
|
|
+ });
|
|
|
|
|
+
|
|
|
it("returns 401 when password is incorrect", async () => {
|
|
it("returns 401 when password is incorrect", async () => {
|
|
|
const user = {
|
|
const user = {
|
|
|
_id: "507f1f77bcf86cd799439012",
|
|
_id: "507f1f77bcf86cd799439012",
|