@@ -9,6 +9,9 @@ describe('Posts API', () => {
99 let testUser : any ;
1010
1111 beforeEach ( async ( ) => {
12+ // Reset all mocks before each test
13+ vi . clearAllMocks ( ) ;
14+
1215 // Mock user creation for unit tests where DB is not available
1316 if ( process . env . MOCK_DB === 'true' ) {
1417 testUser = {
@@ -32,7 +35,7 @@ describe('Posts API', () => {
3235 ...args . data ,
3336 createdAt : new Date ( ) ,
3437 updatedAt : new Date ( ) ,
35- user : testUser
38+ creator : testUser
3639 } ) ) ;
3740 } else {
3841 testUser = await createTestUser ( ) ;
@@ -41,6 +44,9 @@ describe('Posts API', () => {
4144
4245 describe ( 'GET /api/posts' , ( ) => {
4346 it ( 'should return empty array when no posts exist' , async ( ) => {
47+ prisma . post . findMany = vi . fn ( ) . mockResolvedValue ( [ ] ) ;
48+ prisma . post . count = vi . fn ( ) . mockResolvedValue ( 0 ) ;
49+
4450 const request = createMockRequest ( 'http://localhost:3000/api/posts' ) ;
4551 const response = await GET ( request ) ;
4652 const { status, data } = await parseResponse ( response ) ;
@@ -51,29 +57,12 @@ describe('Posts API', () => {
5157 } ) ;
5258
5359 it ( 'should return posts with pagination' , async ( ) => {
54- if ( process . env . MOCK_DB === 'true' ) {
55- prisma . post . findMany = vi . fn ( ) . mockResolvedValue ( [ {
56- id : 'post_123' ,
57- title : 'Test Post' ,
58- user : testUser
59- } ] ) ;
60- prisma . post . count = vi . fn ( ) . mockResolvedValue ( 1 ) ;
61- } else {
62- // Ensure test user exists before creating the post
63- const user = await createTestUser ( ) ;
64- await prisma . post . create ( {
65- data : {
66- userId : user . id ,
67- type : 'giveaway' ,
68- title : 'Test Post' ,
69- slug : 'test-post' ,
70- description :
71- 'A test post description that is long enough to meet requirements.' ,
72- category : 'electronics' ,
73- endsAt : new Date ( Date . now ( ) + 7 * 24 * 60 * 60 * 1000 ) ,
74- } ,
75- } ) ;
76- }
60+ prisma . post . findMany = vi . fn ( ) . mockResolvedValue ( [ {
61+ id : 'post_123' ,
62+ title : 'Test Post' ,
63+ creator : testUser
64+ } ] ) ;
65+ prisma . post . count = vi . fn ( ) . mockResolvedValue ( 1 ) ;
7766
7867 const request = createMockRequest (
7968 'http://localhost:3000/api/posts?page=1&limit=10' ,
@@ -101,6 +90,18 @@ describe('Posts API', () => {
10190 endsAt : new Date ( Date . now ( ) + 7 * 24 * 60 * 60 * 1000 ) . toISOString ( ) ,
10291 } ;
10392
93+ const mockCreatedPost = {
94+ id : 'post_new_123' ,
95+ ...postData ,
96+ endsAt : new Date ( postData . endsAt ) ,
97+ createdAt : new Date ( ) ,
98+ updatedAt : new Date ( ) ,
99+ creator : testUser ,
100+ creatorId : testUser . id ,
101+ } ;
102+
103+ prisma . post . create = vi . fn ( ) . mockResolvedValue ( mockCreatedPost ) ;
104+
104105 const request = createMockRequest ( 'http://localhost:3000/api/posts' , {
105106 method : 'POST' ,
106107 body : postData ,
0 commit comments