@@ -14,6 +14,16 @@ if (!process.env.EXAMPLE_SERVER) {
14
14
process . exit ( 1 ) ;
15
15
}
16
16
17
+ async function getBody ( response ) {
18
+ let responseBody = '' ;
19
+ // eslint-disable-next-line no-restricted-syntax
20
+ for await ( const chunk of response ) {
21
+ responseBody += chunk ;
22
+ }
23
+ expect ( responseBody ) . not . toBe ( '' ) ;
24
+ return JSON . parse ( responseBody ) ;
25
+ }
26
+
17
27
// https://gist.github.com/krnlde/797e5e0a6f12cc9bd563123756fc101f
18
28
http . get [ promisify . custom ] = function getAsync ( options ) {
19
29
return new Promise ( ( resolve , reject ) => {
@@ -28,6 +38,22 @@ http.get[promisify.custom] = function getAsync(options) {
28
38
} ) ;
29
39
} ;
30
40
41
+ function post ( url , body , options ) {
42
+ return new Promise ( ( resolve , reject ) => {
43
+ const request = http
44
+ . request ( url , { method : 'post' , ...options } , response => {
45
+ response . end = new Promise ( res => {
46
+ response . on ( 'end' , res ) ;
47
+ } ) ;
48
+ resolve ( response ) ;
49
+ } )
50
+ . on ( 'error' , reject ) ;
51
+
52
+ request . write ( body ) ;
53
+ request . end ( ) ;
54
+ } ) ;
55
+ }
56
+
31
57
const get = promisify ( http . get ) ;
32
58
33
59
const randomApiKey = 'a-random-readme-api-key' ;
@@ -142,12 +168,7 @@ describe('Metrics SDK Integration Tests', () => {
142
168
expect ( req . url ) . toBe ( '/v1/request' ) ;
143
169
expect ( req . headers . authorization ) . toBe ( 'Basic YS1yYW5kb20tcmVhZG1lLWFwaS1rZXk6' ) ;
144
170
145
- let body = '' ;
146
- // eslint-disable-next-line no-restricted-syntax
147
- for await ( const chunk of req ) {
148
- body += chunk ;
149
- }
150
- body = JSON . parse ( body ) ;
171
+ const body = await getBody ( req ) ;
151
172
const [ har ] = body ;
152
173
153
174
// Check for a uuid
@@ -193,4 +214,26 @@ describe('Metrics SDK Integration Tests', () => {
193
214
const responseHeaders = caseless ( arrayToObject ( response . headers ) ) ;
194
215
expect ( responseHeaders . get ( 'content-type' ) ) . toMatch ( / a p p l i c a t i o n \/ j s o n ( ; \s ? c h a r s e t = u t f - 8 ) ? / ) ;
195
216
} ) ;
217
+
218
+ it ( 'should process the http POST body' , async ( ) => {
219
+ const postData = JSON . stringify ( { user :
{ email :
'[email protected] ' } } ) ;
220
+ await post ( `http://localhost:${ PORT } /` , postData , {
221
+ headers : {
222
+ 'content-type' : 'application/json' ,
223
+ } ,
224
+ } ) ;
225
+
226
+ const [ req ] = await once ( metricsServer , 'request' ) ;
227
+
228
+ const body = await getBody ( req ) ;
229
+ const [ har ] = body ;
230
+
231
+ const { request, response } = har . request . log . entries [ 0 ] ;
232
+ expect ( request . method ) . toBe ( 'POST' ) ;
233
+ expect ( response . status ) . toBe ( 200 ) ;
234
+ expect ( request . postData ) . toStrictEqual ( {
235
+ mimeType : 'application/json' ,
236
+ text : postData ,
237
+ } ) ;
238
+ } ) ;
196
239
} ) ;
0 commit comments