|
| 1 | +import { QueryResult } from 'pg'; |
| 2 | +import { User } from '@/types'; |
| 3 | + |
| 4 | +/** |
| 5 | + * PostgreSQL 쿼리를 모킹하기 위한 mock Pool 객체 |
| 6 | + * |
| 7 | + * @description Jest 테스트에서 pg.Pool의 query 메서드를 모킹하는 데 사용됩니다. |
| 8 | + * @example |
| 9 | + * ```typescript |
| 10 | + * // 성공적인 쿼리 결과 모킹 |
| 11 | + * mockPool.query.mockResolvedValue(createMockQueryResult([{ id: 1, name: 'test' }])); |
| 12 | + * |
| 13 | + * // 에러 발생 모킹 |
| 14 | + * mockPool.query.mockRejectedValue(new Error('Database error')); |
| 15 | + * ``` |
| 16 | + */ |
| 17 | +export const mockPool: { |
| 18 | + query: jest.Mock<Promise<QueryResult<Record<string, unknown>>>, unknown[]>; |
| 19 | +} = { |
| 20 | + query: jest.fn(), |
| 21 | +}; |
| 22 | + |
| 23 | +/** |
| 24 | + * 테스트용 모의 사용자 데이터, User 객체 |
| 25 | + * |
| 26 | + * @description 인증 관련 (미들웨어, QR 로그인 등) 유닛 테스트에서 공통적으로 사용되는 mock User 객체입니다. |
| 27 | + */ |
| 28 | +export const mockUser: User = { |
| 29 | + id: 1, |
| 30 | + velog_uuid: 'uuid-1', |
| 31 | + access_token: 'encrypted-access-token', |
| 32 | + refresh_token: 'encrypted-refresh-token', |
| 33 | + |
| 34 | + username: 'nuung', |
| 35 | + thumbnail: 'https://nuung.com/test.jpg', |
| 36 | + group_id: 1, |
| 37 | + is_active: true, |
| 38 | + created_at: new Date('2024-01-01T00:00:00Z'), |
| 39 | + updated_at: new Date('2024-01-01T00:00:00Z'), |
| 40 | +}; |
| 41 | + |
| 42 | +/** |
| 43 | + * pg의 QueryResult 타입을 만족하는 mock 객체를 생성하기 위한 헬퍼 함수 |
| 44 | + * |
| 45 | + * @template T - 쿼리 결과 row의 타입 (Record<string, unknown>를 확장해야 함) |
| 46 | + * @param rows - 모킹할 데이터베이스 행들의 배열 |
| 47 | + * @returns PostgreSQL QueryResult 형태의 mock 객체 |
| 48 | + * |
| 49 | + * @description |
| 50 | + * PostgreSQL의 실제 쿼리 결과와 동일한 구조를 가진 mock 객체를 생성합니다. |
| 51 | + * Jest 테스트에서 데이터베이스 쿼리 결과를 모킹할 때 사용됩니다. |
| 52 | + * |
| 53 | + * @example |
| 54 | + * ```typescript |
| 55 | + * // 사용자 데이터 모킹 |
| 56 | + * const mockUsers = [ |
| 57 | + * { id: 1, name: 'John', email: 'john@example.com' }, |
| 58 | + * { id: 2, name: 'Jane', email: 'jane@example.com' } |
| 59 | + * ]; |
| 60 | + * const result = createMockQueryResult(mockUsers); |
| 61 | + * |
| 62 | + * // 빈 결과 모킹 |
| 63 | + * const emptyResult = createMockQueryResult([]); |
| 64 | + * |
| 65 | + * // Jest mock에서 사용 |
| 66 | + * mockPool.query.mockResolvedValue(createMockQueryResult(mockUsers)); |
| 67 | + * ``` |
| 68 | + */ |
| 69 | +export function createMockQueryResult<T extends Record<string, unknown>>(rows: T[]): QueryResult<T> { |
| 70 | + return { |
| 71 | + rows, |
| 72 | + rowCount: rows.length, |
| 73 | + command: '', |
| 74 | + oid: 0, |
| 75 | + fields: [], |
| 76 | + } satisfies QueryResult<T>; |
| 77 | +} |
0 commit comments