All files / src/test-utils api-test-helpers.ts

64.36% Statements 177/275
100% Branches 7/7
33.33% Functions 2/6
64.36% Lines 177/275

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 2761x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 153x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 1061x 625x 2x 2x 625x 564x 564x 625x 1061x 1061x 1061x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 840x 840x 840x 840x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                     1x 1x 1x 1x 1x 1x 1x                                                         1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x                       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
/**
 * Test utilities for API route testing
 * Provides helpers for creating mock requests, responses, and sessions
 */
 
import { NextRequest, NextResponse } from "next/server";
 
/**
 * Create a mock NextRequest for API testing
 */
export function createMockRequest(
  method: string,
  url: string,
  options: {
    body?: unknown;
    rawBody?: string;
    headers?: Record<string, string>;
    searchParams?: Record<string, string>;
  } = {}
): NextRequest {
  const { body, rawBody, headers = {}, searchParams = {} } = options;
 
  // Build URL with search params
  const urlObj = new URL(url, "http://localhost:3000");
  Object.entries(searchParams).forEach(([key, value]) => {
    urlObj.searchParams.set(key, value);
  });
 
  const requestInit = {
    method,
    headers: {
      "Content-Type": "application/json",
      ...headers
    }
  } as { method: string; headers: Record<string, string>; body?: string };
 
  if (method !== "GET") {
    if (rawBody !== undefined) {
      // Use raw body string directly (for testing invalid JSON)
      requestInit.body = rawBody;
    } else if (body) {
      requestInit.body = JSON.stringify(body);
    }
  }
 
  return new NextRequest(urlObj, requestInit);
}
 
/**
 * Generic API response type for tests
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type ApiResponse = Record<string, any>;
 
/**
 * Parse JSON response from NextResponse
 */
export async function parseJsonResponse<T = ApiResponse>(
  response: Response
): Promise<T> {
  return response.json() as Promise<T>;
}
 
/**
 * Mock session data for authenticated requests
 * Note: id is numeric to match the next-auth configuration in this project
 */
export const mockUserSession = {
  user: {
    id: 1,
    email: "test@example.com",
    name: "Test User",
    role: "USER" as const
  },
  expires: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
};
 
export const mockAdminSession = {
  user: {
    id: 2,
    email: "admin@example.com",
    name: "Admin User",
    role: "ADMIN" as const
  },
  expires: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
};
 
/**
 * Mock Prisma client for testing
 * Use jest.mock('@/lib/prisma') in your test file and then
 * import this to set up return values
 */
export const createMockPrismaClient = () => ({
  user: {
    findUnique: jest.fn(),
    findMany: jest.fn(),
    create: jest.fn(),
    update: jest.fn(),
    delete: jest.fn(),
    count: jest.fn()
  },
  product: {
    findUnique: jest.fn(),
    findMany: jest.fn(),
    create: jest.fn(),
    update: jest.fn(),
    delete: jest.fn(),
    count: jest.fn()
  },
  cart: {
    findUnique: jest.fn(),
    findMany: jest.fn(),
    create: jest.fn(),
    update: jest.fn(),
    delete: jest.fn(),
    deleteMany: jest.fn()
  },
  order: {
    findUnique: jest.fn(),
    findMany: jest.fn(),
    create: jest.fn(),
    update: jest.fn(),
    count: jest.fn()
  },
  orderItem: {
    createMany: jest.fn()
  },
  category: {
    findUnique: jest.fn(),
    findMany: jest.fn(),
    create: jest.fn(),
    update: jest.fn(),
    delete: jest.fn()
  },
  review: {
    findMany: jest.fn(),
    create: jest.fn(),
    delete: jest.fn()
  },
  wishlist: {
    findUnique: jest.fn(),
    findMany: jest.fn(),
    create: jest.fn(),
    delete: jest.fn()
  },
  $transaction: jest.fn((fn) => fn({
    user: { findUnique: jest.fn(), create: jest.fn() },
    cart: { deleteMany: jest.fn() },
    order: { create: jest.fn() },
    orderItem: { createMany: jest.fn() }
  }))
});
 
/**
 * Create mock auth utilities
 * Reduces boilerplate for authentication-related mocks
 */
export const createMockAuthUtils = (options: {
  isAuthenticated?: boolean;
  isAdmin?: boolean;
  userId?: string;
} = {}) => {
  const { isAuthenticated = false, isAdmin = false, userId = "user-123" } = options;

  return {
    requireAuth: jest.fn().mockResolvedValue(
      isAuthenticated
        ? { id: userId, email: "test@example.com", role: isAdmin ? "ADMIN" : "USER" }
        : Promise.reject(new Error("Unauthorized"))
    ),
    requireAdminRole: jest.fn().mockResolvedValue(
      isAdmin
        ? { id: userId, email: "admin@example.com", role: "ADMIN" }
        : Promise.reject(new Error("Admin access required"))
    ),
    handleAuthError: jest.fn((error) => {
      if (error.message === "Unauthorized" || error.message === "Admin access required") {
        return NextResponse.json(
          { error: error.message },
          { status: error.message === "Unauthorized" ? 401 : 403 }
        );
      }
      return null;
    })
  };
};
 
/**
 * Create mock security headers
 * Standard mock for security-headers module
 */
export const createMockSecurityHeaders = () => ({
  addSecurityHeaders: jest.fn((response) => response)
});
 
/**
 * Setup common mocks for API tests
 * Call this in beforeEach to reset mocks and set common behaviors
 */
export const setupApiTestMocks = (prisma: ReturnType<typeof createMockPrismaClient>) => {
  // Clear all mocks
  Object.values(prisma).forEach((model) => {
    if (typeof model === "object" && model !== null) {
      Object.values(model).forEach((method) => {
        if (typeof method === "function" && "mockReset" in method) {
          (method as jest.Mock).mockReset();
        }
      });
    }
  });
};
 
/**
 * Sample test data
 */
export const testData = {
  user: {
    id: "user-123",
    email: "test@example.com",
    name: "Test User",
    password: "$2a$10$hashedpassword", // bcrypt hash
    role: "USER",
    createdAt: new Date("2024-01-01"),
    updatedAt: new Date("2024-01-01")
  },
  product: {
    id: 1,
    title: "Test Product",
    description: "A test product description",
    price: 100,
    discountedPrice: 80,
    stock: 10,
    sku: "TEST-001",
    categoryId: 1,
    createdAt: new Date("2024-01-01"),
    updatedAt: new Date("2024-01-01"),
    images: [
      { id: 1, url: "/images/test.jpg", thumbnailUrl: "/images/test-thumb.jpg", order: 0, productId: 1 },
    ],
    category: {
      id: 1,
      title: "Test Category",
      slug: "test-category"
    },
    reviews: []
  },
  cartItem: {
    id: 1,
    userId: "user-123",
    productId: 1,
    quantity: 2,
    deviceId: "device-123",
    syncedAt: new Date("2024-01-01"),
    createdAt: new Date("2024-01-01"),
    updatedAt: new Date("2024-01-01")
  },
  order: {
    id: 1,
    userId: "user-123",
    status: "PROCESSING",
    total: 160,
    shippingAddress: "123 Test St",
    createdAt: new Date("2024-01-01"),
    updatedAt: new Date("2024-01-01"),
    items: [
      {
        id: 1,
        orderId: 1,
        productId: 1,
        quantity: 2,
        price: 80
      },
    ]
  }
};