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