From 2339d790b2199249c58c7c206e61a103e1fccf7e Mon Sep 17 00:00:00 2001 From: YaroslavLys <74725159+YaroslavLys@users.noreply.github.com> Date: Tue, 29 Oct 2024 12:21:59 +0200 Subject: [PATCH] Fixed bug when the user is marked as offline even if they have at least one session open (#939) * Fixed bug when the user is deleted from usersOnline too early * Added tests for user disconnect from ther socket server --- src/event-handlers/activityHandler.js | 2 +- .../unit/event-handlers/activityHandler.spec.js | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/event-handlers/activityHandler.js b/src/event-handlers/activityHandler.js index e114f692..e14de85d 100644 --- a/src/event-handlers/activityHandler.js +++ b/src/event-handlers/activityHandler.js @@ -6,7 +6,7 @@ module.exports = (io, socket, usersOnline) => { } const disconnect = () => { - if (socket.user) { + if (socket.user && !io.sockets.adapter.rooms.has(socket.user.id)) { usersOnline.delete(socket.user.id) io.emit('usersOnline', Array.from(usersOnline)) } diff --git a/src/test/unit/event-handlers/activityHandler.spec.js b/src/test/unit/event-handlers/activityHandler.spec.js index 21506365..b3a49873 100644 --- a/src/test/unit/event-handlers/activityHandler.spec.js +++ b/src/test/unit/event-handlers/activityHandler.spec.js @@ -4,7 +4,7 @@ describe('activityHandler', () => { let io, socket, usersOnline beforeEach(() => { - io = { emit: jest.fn() } + io = { emit: jest.fn(), sockets: { adapter: { rooms: new Map() } } } socket = { join: jest.fn(), on: jest.fn(), @@ -36,6 +36,18 @@ describe('activityHandler', () => { expect(io.emit).toHaveBeenCalledWith('usersOnline', Array.from(usersOnline)) }) + test('should not delete the user from usersOnline when the user has at least one active session', () => { + usersOnline.add('user1') + io.sockets.adapter.rooms.set('user1', 'socketId') + + const disconnectCallback = socket.on.mock.calls.find(([event]) => event === 'disconnect')[1] + + disconnectCallback() + + expect(usersOnline.has('user1')).toBe(true) + expect(io.emit).not.toHaveBeenCalled() + }) + test('should call disconnect and do nothing if socket.user is undefined', () => { socket.user = undefined