import WebSocketTransport from 'src/transport/websocket' ; describe ( 'websocket transport' , ( ) => { const OriginalWebSocket = WebSocket ; const constructor = jest . fn ( ) ; const send = jest . fn ( ) ; let onmessage ; const listener = jest . fn ( ) ; class MockWebSocket { constructor ( ... args ) { constructor ( ... args ) ; } send ( ... args ) { send ( ... args ) ; } set onmessage ( value ) { onmessage = value ; } } let transport ; beforeEach ( ( ) => { global . WebSocket = MockWebSocket ; transport = new WebSocketTransport ( ) ; } ) ; afterEach ( ( ) => { global . WebSocket = OriginalWebSocket ; } ) ; test ( 'connects to websocket' , ( ) => { expect ( constructor ) . toHaveBeenCalledWith ( 'ws://localhost' ) ; } ) ; test ( 'send method sends channel and args to websocket' , ( ) => { transport . send ( 'channel' , 'arg1' , 'arg2' ) ; expect ( send ) . toHaveBeenCalledWith ( '["channel","arg1","arg2"]' ) ; } ) ; test ( 'sent message is JSON stringified' , ( ) => { transport . send ( 'channel' , { complex : { object : true } } ) ; expect ( send ) . toHaveBeenCalledWith ( '["channel",{"complex":{"object":true}}]' ) ; } ) ; test ( 'receive message if you subscribe to chanel' , ( ) => { transport . on ( 'channel' , listener ) ; onmessage ( { data : JSON . stringify ( [ 'channel' , [ 'arg1' , 'arg2' ] ] ) } ) ; expect ( listener ) . toHaveBeenCalledWith ( [ 'arg1' , 'arg2' ] ) ; onmessage ( { data : JSON . stringify ( [ 'channel' , [ 'arg3' ] ] ) } ) ; expect ( listener ) . toHaveBeenCalledWith ( [ 'arg3' ] ) ; } ) ; test ( "don't receive messages for channels you did not subscribe" , ( ) => { transport . on ( 'channel' , listener ) ; onmessage ( { data : JSON . stringify ( [ 'other-channel' , [ 'arg1' , 'arg2' ] ] ) } ) ; expect ( listener ) . not . toHaveBeenCalled ( ) ; } ) ; } ) ;