2

I am creating a mean stack application using nestjs. In nestjs, I am using websockets. I don't know how to test websockets in postman.

Normally, I have a test route url in postman and get o/p like: "http://localhost:3000/{routeUrl}", but how to give using sockets i am confused

example :

@WebSocketGateway() 

export class MessagesGateway implements  OnGatewayDisconnect {

  constructor(@InjectModel(Message) private readonly messagesModel:
 ModelType<Message>,
               @InjectModel(Room) private readonly roomsModel: ModelType<Room>,
               @InjectModel(User) private readonly usersModel: ModelType<User>) { // <1>   }
 
   async handleDisconnect(client: Socket) { // <2>
     const user = await this.usersModel.findOne({clientId: client.id});
     if (user) {
       client.server.emit('users-changed', {user: user.nickname, event: 'left'});
       user.clientId = null;
       await this.usersModel.findByIdAndUpdate(user._id, user);
     }   }
 
   @SubscribeMessage('enter-chat-room') // <3>   async
 enterChatRoom(client: Socket, data: { nickname: string, roomId: string
 }) {
     let user = await this.usersModel.findOne({nickname: data.nickname});
     if (!user) {
       user = await this.usersModel.create({nickname: data.nickname, clientId: client.id});
     } else {
       user.clientId = client.id;
       user = await this.usersModel.findByIdAndUpdate(user._id, user, {new: true});
     }
     client.join(data.roomId).broadcast.to(data.roomId)
       .emit('users-changed', {user: user.nickname, event: 'joined'}); // <3>   }
 
   @SubscribeMessage('leave-chat-room') // <4>   async
 leaveChatRoom(client: Socket, data: { nickname: string, roomId: string
 }) {
     const user = await this.usersModel.findOne({nickname: data.nickname});
     client.broadcast.to(data.roomId).emit('users-changed', {user: user.nickname, event: 'left'}); // <3>
     client.leave(data.roomId);   }
 
   @SubscribeMessage('add-message') // <5>   async addMessage(client:
 Socket, message: Message) {
     message.owner = await this.usersModel.findOne({clientId: client.id});
     message.created = new Date();
     message = await this.messagesModel.create(message);
     client.server.in(message.room as string).emit('message', message);   } }

3 Answers 3

0

In your case, when you do not specify the path of the WS, it is listening on the same port as the server listening and path does not matter at all.

WS is a different protocol and you have to make the mental switch to this way of thinking.

You will not be able to test WS server with Postman. To do that you have to create your WS client, however, I strongly encourage you to create E2E tests with Nest to test it with the code, not manually.

Sign up to request clarification or add additional context in comments.

3 Comments

when we create a client on the server for e2e do you think we need to run server WebSocket because testing on local is good and great but on circle CI, GitHub PR test, test coverage, etc will fail
it will not fail. I am successfully running e2e tests on our CI Port may be an issue but can be easily solved with simple function finding available port.
@MarekUrbanowicz, could you take a look please stackoverflow.com/questions/65286333/…
0

Here's my working example:

  import * as WebSocket from 'ws'
  beforeAll(async () => {
    const moduleFixture = await Test.createTestingModule({
      imports: [
        SocketModule,
      ],
    })
      .compile()

    app = moduleFixture.createNestApplication()
    app.useWebSocketAdapter(new WsAdapter(app))
    await app.init()
  })

  it('should connect successfully', (done) => {
    const address = app.getHttpServer().listen().address()
    const baseAddress = `http://[${address.address}]:${address.port}`

    const socket = new WebSocket(baseAddress)

    socket.on('open', () => {
      console.log('I am connected! YEAAAP')
      done()
    })

    socket.on('close', (code, reason) => {
      done({ code, reason })
    })

    socket.on ('error', (error) => {
      done(error)
    })
  })

Detail about this answer is discussed here

Comments

0

The second args of cb from onConnection incomingMessage

this.server.on('connection', (socket:WebSocket, incomingMessage) => {
   console.log(incomingMessage)
   console.log('connection')
})

incomingMessage.url
'/v2/ta-websocket/22950b69-7928-43b9-8c38-efc5c126208e'

screen shot here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.