guanw / sr_server

0 stars 0 forks source link

refactor index.ts #7

Open guanw opened 1 month ago

guanw commented 1 month ago

into server.ts and index.ts so server.ts can be used in unit test to mock client/server socket interaction and verify change works

guanw commented 1 month ago

something like

// server.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// Example event handling
io.on('connection', (socket) => {
  console.log(`Client connected: ${socket.id}`);

  // Echo event for testing
  socket.on('echo', (message) => {
    socket.emit('echo', message);
  });

  // Broadcast message
  socket.on('broadcast', (message) => {
    socket.broadcast.emit('broadcast', message);
  });

  socket.on('disconnect', () => {
    console.log(`Client disconnected: ${socket.id}`);
  });
});

module.exports = { server, io };
// test/integration.test.js
const io = require('socket.io-client');
const { server } = require('../server'); // Assuming server.js is in the root directory
const chai = require('chai');
const expect = chai.expect;

const socketUrl = 'http://localhost:3000';

let clientSocket;

describe('Socket.IO Server Integration Tests', () => {
  // Start the server before running tests
  before((done) => {
    server.listen(3000, done);
  });

  // Clean up the client socket after each test
  afterEach(() => {
    if (clientSocket) clientSocket.disconnect();
  });

  // Close the server after all tests
  after((done) => {
    server.close(done);
  });

  it('should connect to the server and receive a socket ID', (done) => {
    clientSocket = io(socketUrl);
    clientSocket.on('connect', () => {
      expect(clientSocket.id).to.exist; // Test if the client has an ID
      done();
    });
  });

  it('should echo a message back to the client', (done) => {
    clientSocket = io(socketUrl);

    clientSocket.on('connect', () => {
      clientSocket.emit('echo', 'Hello, Server!');
    });

    clientSocket.on('echo', (message) => {
      expect(message).to.equal('Hello, Server!');
      done();
    });
  });

  it('should broadcast a message to other clients', (done) => {
    const secondClient = io(socketUrl);

    secondClient.on('connect', () => {
      clientSocket = io(socketUrl);

      clientSocket.on('connect', () => {
        clientSocket.emit('broadcast', 'Hello, everyone!');
      });

      secondClient.on('broadcast', (message) => {
        expect(message).to.equal('Hello, everyone!');
        secondClient.disconnect();
        done();
      });
    });
  });
});