thoov / mock-socket

Javascript mocking library for WebSockets and Socket.IO
MIT License
797 stars 118 forks source link

Mock-socket only usable from same script/application? #291

Open raketenolli opened 4 years ago

raketenolli commented 4 years ago

This is more of a support question than an actual issue, if applicable please refer to the proper resources for asking this.

I mocked a websocket server similar to the one described in the "Usage" section of the readme.

const { Server } = require('mock-socket');

const fakeURL = 'wss://localhost:8080';
const mockServer = new Server(fakeURL);

for(let i = 0; i < 10; i++) {
    setTimeout(() => {
        mockServer.emit('message', `message #${i} appears after ${i} seconds`);
        console.log(`sending message ${i}`);
    }, (i+10)*1000);
}

setTimeout(() => {
    mockServer.stop();
}, 22000);

If I add a WebSocket directly inside this file, it receives the messages. But if I create a second script

const { WebSocket } = require('mock-socket');

const fakeURL = 'wss://localhost:8080';
var client = new WebSocket(fakeURL);

client.onmessage = message => {
    console.log(message.data);
};

and start it just after launching the first one, I'd expect it to be able to connect to the mocked server at localhost:8080 and receive and display the messages. Instead I get

WebSocket connection to 'wss://localhost:8080/' failed

in the console. Same result if I create an HTML page with a similar <script> and open it just after starting the mock server.

More generally, how can I use mock-socket to test the behavior of web applications that rely on websocket connections for some of their functionality?

raxod502 commented 4 years ago

My understanding is that no server is actually created, and instead the server and client are connected in-memory by doing string matching to see if the "fake URL" provided to server and client is the same. Thus it only works in the same script. However, it is hard to tell for sure because there is no documentation aside from the sparse README :/