@@ -4,6 +4,7 @@ const fs = require('fs');
44const path = require ( 'path' ) ;
55const request = require ( 'supertest' ) ;
66const { app, prisma } = require ( '..' ) ;
7+ const { clearDatabase, createUserWithRole } = require ( './helpers/db' ) ;
78
89const uploadsDir = path . join ( __dirname , '..' , 'uploads' ) ;
910
@@ -13,6 +14,16 @@ beforeAll(() => {
1314 }
1415} ) ;
1516
17+ beforeEach ( async ( ) => {
18+ await clearDatabase ( ) ;
19+ if ( ! fs . existsSync ( uploadsDir ) ) {
20+ fs . mkdirSync ( uploadsDir , { recursive : true } ) ;
21+ }
22+ for ( const file of fs . readdirSync ( uploadsDir ) ) {
23+ fs . unlinkSync ( path . join ( uploadsDir , file ) ) ;
24+ }
25+ } ) ;
26+
1627afterAll ( async ( ) => {
1728 await prisma . $disconnect ( ) ;
1829} ) ;
@@ -41,3 +52,45 @@ test('serves unknown extension as attachment octet-stream', async () => {
4152 expect ( res . headers [ 'content-type' ] ) . toBe ( 'application/octet-stream' ) ;
4253 expect ( res . headers [ 'content-disposition' ] ) . toContain ( 'attachment' ) ;
4354} ) ;
55+
56+ const login = async ( utorid , password ) => {
57+ const res = await request ( app )
58+ . post ( '/auth/tokens' )
59+ . send ( { utorid, password } ) ;
60+ return res . body . token ;
61+ } ;
62+
63+ test ( 'rejects non-image avatar upload' , async ( ) => {
64+ const { user, password } = await createUserWithRole ( 'regular' ) ;
65+ const token = await login ( user . utorid , password ) ;
66+
67+ const res = await request ( app )
68+ . patch ( '/users/me' )
69+ . set ( 'Authorization' , `Bearer ${ token } ` )
70+ . attach ( 'avatar' , Buffer . from ( 'not-an-image' ) , {
71+ filename : 'notevil.txt' ,
72+ contentType : 'text/plain'
73+ } ) ;
74+
75+ expect ( res . status ) . toBe ( 400 ) ;
76+ expect ( res . body ) . toHaveProperty ( 'error' ) ;
77+ expect ( fs . readdirSync ( uploadsDir ) . length ) . toBe ( 0 ) ;
78+ } ) ;
79+
80+ test ( 'accepts image avatar upload and stores file' , async ( ) => {
81+ const { user, password } = await createUserWithRole ( 'regular' ) ;
82+ const token = await login ( user . utorid , password ) ;
83+
84+ const res = await request ( app )
85+ . patch ( '/users/me' )
86+ . set ( 'Authorization' , `Bearer ${ token } ` )
87+ . attach ( 'avatar' , Buffer . from ( [ 0x89 , 0x50 , 0x4e , 0x47 ] ) , {
88+ filename : 'avatar.png' ,
89+ contentType : 'image/png'
90+ } ) ;
91+
92+ expect ( res . status ) . toBe ( 200 ) ;
93+ expect ( res . body ) . toHaveProperty ( 'avatarUrl' ) ;
94+ expect ( res . body . avatarUrl ) . toContain ( '/uploads/' ) ;
95+ expect ( fs . readdirSync ( uploadsDir ) . length ) . toBe ( 1 ) ;
96+ } ) ;
0 commit comments