@@ -8,7 +8,7 @@ import { expect } from 'chai';
88import getGraphQL from 'graphql.js' ;
99import fetch from 'node-fetch' ;
1010
11- import { getRemote } from 'mockttp' ;
11+ import { getRemote , getLocal } from 'mockttp' ;
1212
1313import { delay } from '../src/util/promise' ;
1414
@@ -303,4 +303,78 @@ describe('Integration test', function () {
303303 }
304304 } ) ;
305305 } ) ;
306+
307+ describe ( "client API" , ( ) => {
308+ const mockServer = getLocal ( ) ;
309+
310+ beforeEach ( ( ) => mockServer . start ( ) ) ;
311+ afterEach ( ( ) => mockServer . stop ( ) ) ;
312+
313+ it ( "can send HTTP requests" , async ( ) => {
314+ await mockServer . forAnyRequest ( ) . thenCallback ( async ( request ) => {
315+ expect ( request . method ) . to . equal ( 'POST' ) ;
316+ expect ( request . url ) . to . equal ( `http://localhost:${ mockServer . port } /abc?def` ) ;
317+ expect ( request . rawHeaders ) . to . deep . equal ( [
318+ [ 'host' , `localhost:${ mockServer . port } ` ] ,
319+ [ 'content-length' , '12' ] ,
320+ [ 'TEST-header' , 'Value' ]
321+ ] ) ;
322+ expect ( await request . body . getText ( ) ) . to . equal ( 'Request body' ) ;
323+
324+ return {
325+ statusCode : 200 ,
326+ statusMessage : 'Custom status message' ,
327+ headers : { 'custom-HEADER' : 'custom-VALUE' } ,
328+ rawBody : Buffer . from ( 'Mock response body' )
329+ } ;
330+ } ) ;
331+
332+ const apiResponse = await fetch ( 'http://localhost:45457/client/send' , {
333+ method : 'POST' ,
334+ headers : {
335+ 'origin' : 'https://app.httptoolkit.tech' ,
336+ 'content-type' : 'application/json'
337+ } ,
338+ body : JSON . stringify ( {
339+ request : {
340+ method : 'POST' ,
341+ url : mockServer . urlFor ( '/abc?def' ) ,
342+ headers : [
343+ [ 'host' , `localhost:${ mockServer . port } ` ] ,
344+ [ 'content-length' , '12' ] ,
345+ [ 'TEST-header' , 'Value' ] ,
346+ ] ,
347+ rawBody : Buffer . from ( 'Request body' ) . toString ( 'base64' )
348+ } ,
349+ options : { }
350+ } )
351+ } ) ;
352+
353+ expect ( apiResponse . status ) . to . equal ( 200 ) ;
354+
355+ const apiResponseBody = await apiResponse . text ( ) ;
356+ const responseEvents = apiResponseBody
357+ . split ( '\n' )
358+ . filter ( l => l . trim ( ) . length )
359+ . map ( l => JSON . parse ( l ) ) ;
360+
361+ expect ( responseEvents . length ) . to . equal ( 3 ) ;
362+ expect ( responseEvents [ 0 ] ) . to . deep . equal ( {
363+ type : 'response-head' ,
364+ statusCode : 200 ,
365+ statusMessage : 'Custom status message' ,
366+ headers : [
367+ [ 'custom-HEADER' , 'custom-VALUE' ]
368+ ]
369+ } ) ;
370+
371+ expect ( responseEvents [ 1 ] . type ) . equal ( 'response-body-part' ) ;
372+ expect (
373+ Buffer . from ( responseEvents [ 1 ] . data , 'base64' ) . toString ( 'utf8' )
374+ ) . to . equal ( 'Mock response body' ) ;
375+
376+
377+ expect ( responseEvents [ 2 ] ) . to . deep . equal ( { type : 'response-end' } ) ;
378+ } ) ;
379+ } )
306380} ) ;
0 commit comments