Skip to content

Commit

Permalink
Fixed bug when the user is marked as offline even if they have at lea…
Browse files Browse the repository at this point in the history
…st one session open (#939)

* Fixed bug when the user is deleted from usersOnline too early

* Added tests for user disconnect from ther socket server
  • Loading branch information
YaroslavLys authored Oct 29, 2024
1 parent dcb6686 commit 2339d79
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/event-handlers/activityHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}
Expand Down
14 changes: 13 additions & 1 deletion src/test/unit/event-handlers/activityHandler.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -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

Expand Down

0 comments on commit 2339d79

Please sign in to comment.