prices-route.test.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { beforeEach, describe, expect, it, vi } from "vitest";
  2. const mocks = vi.hoisted(() => ({
  3. getSession: vi.fn(),
  4. getModelPricesPaginated: vi.fn(),
  5. }));
  6. vi.mock("@/lib/auth", () => ({
  7. getSession: mocks.getSession,
  8. }));
  9. vi.mock("@/actions/model-prices", () => ({
  10. getModelPricesPaginated: mocks.getModelPricesPaginated,
  11. }));
  12. describe("GET /api/prices", () => {
  13. beforeEach(() => {
  14. vi.clearAllMocks();
  15. });
  16. it("returns 403 when session is missing", async () => {
  17. mocks.getSession.mockResolvedValue(null);
  18. const { GET } = await import("@/app/api/prices/route");
  19. const response = await GET({ url: "http://localhost/api/prices" } as any);
  20. expect(response.status).toBe(403);
  21. });
  22. it("returns 403 when user is not admin", async () => {
  23. mocks.getSession.mockResolvedValue({ user: { role: "user" } });
  24. const { GET } = await import("@/app/api/prices/route");
  25. const response = await GET({ url: "http://localhost/api/prices" } as any);
  26. expect(response.status).toBe(403);
  27. });
  28. it("returns 400 when page is NaN", async () => {
  29. mocks.getSession.mockResolvedValue({ user: { role: "admin" } });
  30. const { GET } = await import("@/app/api/prices/route");
  31. const response = await GET({ url: "http://localhost/api/prices?page=abc&pageSize=50" } as any);
  32. expect(response.status).toBe(400);
  33. });
  34. it("returns 400 when pageSize is NaN", async () => {
  35. mocks.getSession.mockResolvedValue({ user: { role: "admin" } });
  36. const { GET } = await import("@/app/api/prices/route");
  37. const response = await GET({ url: "http://localhost/api/prices?page=1&pageSize=abc" } as any);
  38. expect(response.status).toBe(400);
  39. });
  40. it("returns ok=true when params are valid", async () => {
  41. mocks.getSession.mockResolvedValue({ user: { role: "admin" } });
  42. mocks.getModelPricesPaginated.mockResolvedValue({
  43. ok: true,
  44. data: {
  45. data: [],
  46. total: 0,
  47. page: 1,
  48. pageSize: 50,
  49. totalPages: 0,
  50. },
  51. });
  52. const { GET } = await import("@/app/api/prices/route");
  53. const response = await GET({ url: "http://localhost/api/prices?page=1&pageSize=50" } as any);
  54. expect(response.status).toBe(200);
  55. const body = await response.json();
  56. expect(body.ok).toBe(true);
  57. expect(mocks.getModelPricesPaginated).toHaveBeenCalledWith(
  58. expect.objectContaining({ page: 1, pageSize: 50 })
  59. );
  60. });
  61. });