I wrote a simple server adding a todo using sockets.
// todos.gateway.ts
import {
SubscribeMessage,
WebSocketGateway,
OnGatewayInit,
WebSocketServer,
OnGatewayConnection,
OnGatewayDisconnect,
} from '@nestjs/websockets';
import { Logger } from '@nestjs/common';
import { Socket, Server } from 'socket.io';
import { Todos } from './todos.entity';
import { TodosService } from './todos.service';
@WebSocketGateway()
export class TodosGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
constructor(private todosService: TodosService) {}
@WebSocketServer() server: Server;
private logger: Logger = new Logger('TodosGateway');
@SubscribeMessage('listToDoToServer')
async handleListToDos(client: Socket, payload: string, data: { room: string; id: number }) {
client.join(data.room);
this.logger.log(`Room id: ${data.id}, Client id: ${data.id}`);
const listDoto = await this.todosService.getToDos();
this.server.to(data.room).emit('listToDoToClient', listDoto);
}
@SubscribeMessage('leaveRoom')
handleRoomLeave(client: Socket, payload: string, room: string) {
client.leave(room);
this.logger.log(`Client leave room: ${room}`);
}
afterInit(server: Server) {
this.logger.log('Init');
}
handleDisconnect(client: Socket) {
this.logger.log(`Client disconnected: ${client.id}`);
}
handleConnection(client: Socket, ...args: any[]) {
this.logger.log(`Client connected: ${client.id}`);
}
}
// todos.gateway.spec.ts
import { Test, TestingModule } from '@nestjs/testing';
import { TodosGateway } from './todos.gateway';
describe('TodosGateway', () => {
let gateway: TodosGateway;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [TodosGateway],
}).compile();
gateway = module.get<TodosGateway>(TodosGateway);
});
it('should be defined', () => {
expect(gateway).toBeDefined();
});
});
How to test sockets? I understand that you need to create mock functions, and which one I don’t understand.
I could not find information on socket testing in the documentation. Also, those examples that I find through Google did not suit me.
Aucun commentaire:
Enregistrer un commentaire