@@ -125,3 +125,63 @@ test('captures errors on start', async (t) => {
125
125
t . teardown ( app . close . bind ( app ) )
126
126
t . teardown ( app2 . close . bind ( app2 ) )
127
127
} )
128
+
129
+ test ( 'getWebSocketStream' , async ( t ) => {
130
+ t . plan ( 7 )
131
+
132
+ const origin = createServer ( )
133
+ const wss = new WebSocket . Server ( { server : origin } )
134
+ t . teardown ( wss . close . bind ( wss ) )
135
+ t . teardown ( origin . close . bind ( origin ) )
136
+
137
+ const serverMessages = [ ]
138
+ wss . on ( 'connection' , ( ws , request ) => {
139
+ t . equal ( ws . protocol , subprotocolValue )
140
+ t . equal ( request . headers . cookie , cookieValue )
141
+ ws . on ( 'message' , ( message , binary ) => {
142
+ serverMessages . push ( [ message . toString ( ) , binary ] )
143
+ // echo
144
+ ws . send ( message , { binary } )
145
+ } )
146
+ } )
147
+
148
+ await promisify ( origin . listen . bind ( origin ) ) ( { port : 0 } )
149
+
150
+ const server = Fastify ( )
151
+ server . register ( proxy , {
152
+ upstream : '' ,
153
+ replyOptions : {
154
+ getUpstream : function ( original , base ) {
155
+ return `http://localhost:${ origin . address ( ) . port } `
156
+ }
157
+ } ,
158
+ websocket : true
159
+ } )
160
+
161
+ await server . listen ( { port : 0 } )
162
+ t . teardown ( server . close . bind ( server ) )
163
+
164
+ const options = { headers : { cookie : cookieValue } }
165
+ const ws = new WebSocket ( `ws://localhost:${ server . server . address ( ) . port } ` , [ subprotocolValue ] , options )
166
+ await once ( ws , 'open' )
167
+
168
+ ws . send ( 'hello' , { binary : false } )
169
+ const [ reply0 , binary0 ] = await once ( ws , 'message' )
170
+ t . equal ( reply0 . toString ( ) , 'hello' )
171
+ t . equal ( binary0 , false )
172
+
173
+ ws . send ( Buffer . from ( 'fastify' ) , { binary : true } )
174
+ const [ reply1 , binary1 ] = await once ( ws , 'message' )
175
+ t . equal ( reply1 . toString ( ) , 'fastify' )
176
+ t . equal ( binary1 , true )
177
+
178
+ t . strictSame ( serverMessages , [
179
+ [ 'hello' , false ] ,
180
+ [ 'fastify' , true ]
181
+ ] )
182
+
183
+ await Promise . all ( [
184
+ once ( ws , 'close' ) ,
185
+ server . close ( )
186
+ ] )
187
+ } )
0 commit comments