Skip to content

Commit

Permalink
more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
sinamics committed Dec 11, 2023
1 parent 19b99ae commit 2bf7f26
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions src/pages/api/__tests__/v1/user/user.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,20 @@ jest.mock("~/server/db", () => ({
}));

describe("createUserHandler", () => {
afterEach(() => {
// Restores all mocks back to their original value.
// only works when the mock was created with jest.spyOn;
jest.restoreAllMocks();
});
// Helper function to create a mock response object
const createMockRes = () =>
({
status: jest.fn().mockReturnThis(),
json: jest.fn(),
end: jest.fn(),
setHeader: jest.fn(),
}) as unknown as NextApiResponse;

it("should create a user successfully", async () => {
prisma.user.count = jest.fn().mockResolvedValue(0);

Expand Down Expand Up @@ -61,4 +75,45 @@ describe("createUserHandler", () => {
expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith({ id: "newUserId" });
});

it("should respond 401 when decryptAndVerifyToken fails", async () => {
prisma.user.count = jest.fn().mockResolvedValue(1);

// Mock the decryption to fail
(encryptionModule.decryptAndVerifyToken as jest.Mock).mockRejectedValue(
new Error("Invalid token"),
);

const req = {
method: "POST",
headers: { "x-ztnet-auth": "invalidApiKey" },
query: { id: "networkId" },
} as unknown as NextApiRequest;

const res = {
status: jest.fn().mockReturnThis(),
json: jest.fn(),
end: jest.fn(),
setHeader: jest.fn(), // Mock `setHeader` if rate limiter uses it
} as unknown as NextApiResponse;

await createUserHandler(req, res);

expect(res.status).toHaveBeenCalledWith(401);
expect(res.json).toHaveBeenCalledWith({ error: "Invalid token" });
});

it("should allow only POST method", async () => {
const methods = ["GET", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"];
const req = {} as NextApiRequest;
const res = createMockRes();

for (const method of methods) {
req.method = method;
await createUserHandler(req, res);

expect(res.status).toHaveBeenCalledWith(405);
expect(res.end).toHaveBeenCalled();
}
});
});

0 comments on commit 2bf7f26

Please sign in to comment.