Mocking Websocket Message Events

How to mock web socket message events in Chrome.

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<ul class="ui-widget"></ul>

CSS

body {
    font-size: 0.8em;
    margin: 2em;
}

ul {
    list-style-type: none;
    padding-left: 0;
    margin-left: 0;
}

JavaScript

(function( $ ) {

    // The global web socket.    
    var sock;
    
    // Some mock data.
    var users = [
        "User 1",
        "User 2",
        "User 3",
        "User 4"
    ];
    
    // Mocks web socket activity by pushing new items onto
    // the mock data array and dispatching a MessageEvent.
    function mockSock() {
        
        users.push( "User " + ( users.length + 1 ) );
        
        // Dispatch the event directly on the web socket object.
        // The event data is expecting the "data" key for the message
        // data that's delivered to handlers.
        sock.dispatchEvent( new MessageEvent( "message", {
            data: {
                topic: "user.insert",
                user: _.last( users )
            }
        }));
        
        // Send another message in 3 seconds.
        _.delay( mockSock, 3000 );
        
    }
       
    $(function() {
        
        // We can create a real web socket instance with a bogus URL.
        // NOTE: This only works in Chrome as it will happily create
        // a web socket in a disconnected state. Other browsers refuse
        // to do so.
        sock = new WebSocket( "ws://mock" );
        
        // This is unchanging production code that doesn't know
        // we're mocking the web socket.
        sock.onmessage = function( e ) {
            var msg = e.data;
            if ( msg.topic === "user.insert" ) {
                $( "<li/>" ).text( msg.user )
                            .appendTo( "ul" );
            }
        };        
        
        $.each( users, function() {
            $( "<li/>" ).text( this )
                        .appendTo( "ul" );
        });
        
        // Starts the mocking activity.        
        mockSock();
        
    });
           
})( jQuery );