#How to test websocket endpoint?

9 messages · Page 1 of 1 (latest)

sick tapir
#

I have an simple chat room websocket server. but how to test it?


@WebSocketGateway({
  cors: {
    origin: process.env.FRONTEND_URL || 'http://localhost:5173',
    credentials: true,
  },
  namespace: 'chats',
})
export class ChatsGateway implements OnGatewayConnection, OnGatewayDisconnect {
  private readonly logger = new Logger(ChatsGateway.name);
  private readonly challengeSubscriptions = new Map<string, Set<string>>();

  @WebSocketServer()
  server: Server;

I just saw the End-to-end testing on doc.

edgy wraithBOT
#

There's a large repository of samples managed by the community.

ashen linden
#

or you can try it on your browser console

#

..................

#

const socket = new WebSocket('ws://localhost:3000/chats'); socket.onopen = () => console.log('Connected to WebSocket'); socket.onmessage = (event) => console.log('Received:', event.data); socket.send(JSON.stringify({ message: "Hello from client!" }));

#

second: you can try to test it with unit testing websockets in nestjs(jest)

#

``import { Test, TestingModule } from '@nestjs/testing';
import { ChatsGateway } from './chats.gateway';
import { Server } from 'socket.io';

describe('ChatsGateway', () => {
let gateway: ChatsGateway;
let server: Server;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [ChatsGateway],
}).compile();

gateway = module.get<ChatsGateway>(ChatsGateway);
server = new Server(); // Mock WebSocket Server
gateway.server = server;

});

it('should be defined', () => {
expect(gateway).toBeDefined();
});

it('should log a message when a client connects', () => {
const mockClient = { id: '1234' } as any;
jest.spyOn(console, 'log');

gateway.handleConnection(mockClient);
expect(console.log).toHaveBeenCalledWith(expect.stringContaining('Client connected'));

});

it('should log a message when a client disconnects', () => {
const mockClient = { id: '1234' } as any;
jest.spyOn(console, 'log');

gateway.handleDisconnect(mockClient);
expect(console.log).toHaveBeenCalledWith(expect.stringContaining('Client disconnected'));

});
});``

edgy wraithBOT
#

This message has been acknowledged by @ashen linden, <t:1739088854:R>