promisify automock socketio | Mock any module with promisify and socket.io-client | Cell 4 | Search

This code sets up a Socket.IO server and client for testing, handling potential port conflicts by retrying server startup if necessary.

Run example

npm run import -- "Check if sockify server is running"

Check if sockify server is running

var tryReset = false;
try {
    var io = sockifyServer(8098);
} catch (e) {
    if (e.code !== 'EADDRINUSE') {
        throw e;
    } else {
        tryReset = true;
    }
}
var fs = sockifyClient(require('fs'), 'fs', 'http://localhost:8098');
if (tryReset) {
    fs.___close();
    var io = sockifyServer(8098);
}

What the code could have been:

// Import required modules
const fs = require('fs');
const { createServer } = require('http');

// Define constants
const LISTEN_PORT = 8098;
const FS_ENDPOINT = `http://localhost:${LISTEN_PORT}`;

/**
 * Attempt to start the server at port LISTEN_PORT.
 * If the port is in use, the function will catch the error, set tryReset to true, and exit.
 * 
 * @returns {Server} The server instance if the port is available.
 * @throws {Error} If the port is unavailable but the error code is not EADDRINUSE.
 */
function startServer() {
    try {
        return createServer().listen(LISTEN_PORT);
    } catch (e) {
        if (e.code!== 'EADDRINUSE') {
            throw e;
        } else {
            return null;
        }
    }
}

// Initialize server and file system
let tryReset = false;
let io = startServer();

if (!io) {
    tryReset = true;
}

// Create a file system client connected to the server at FS_ENDPOINT
const client = require('./sockifyClient')(fs, 'fs', FS_ENDPOINT);

if (tryReset) {
    // If the port is in use, close the client and restart the server
    client.close();
    io = startServer();
    io.listen(LISTEN_PORT);
}

This code snippet sets up a mock Socket.IO server and client for testing purposes.

Here's a breakdown:

  1. Server Setup:

  2. Client Setup:

  3. Retry Server:

In essence:

This code aims to create a reliable test environment by handling potential port conflicts and ensuring a working Socket.IO server and client for testing purposes.