diff --git a/src/lib/stack-client.js b/src/lib/stack-client.js index eb0ee027f..3720a0a8f 100644 --- a/src/lib/stack-client.js +++ b/src/lib/stack-client.js @@ -353,13 +353,23 @@ const getSettingsAppURL = function() { * @returns {Promise} */ const init = function({ cozyClient: client, onCreate, onDelete }) { - cozyClient = client - if (!cozyClient.isLogged) return - initializeRealtime({ - getApp, - onCreate, - onDelete, - cozyClient + cozyClient = client // Setting global variable + let terminateRealtime + const onLogin = () => { + terminateRealtime = initializeRealtime({ + getApp, + onCreate, + onDelete, + cozyClient + }) + } + if (cozyClient.isLogged) { + onLogin() + } + cozyClient.once('logout', () => { + if (terminateRealtime) { + terminateRealtime() + } }) } diff --git a/test/lib/stack-client/stack-client.init.spec.js b/test/lib/stack-client/stack-client.init.spec.js index b66340fd5..f632724af 100644 --- a/test/lib/stack-client/stack-client.init.spec.js +++ b/test/lib/stack-client/stack-client.init.spec.js @@ -4,7 +4,6 @@ import CozyClient from 'cozy-client' import initializeRealtime from 'lib/realtime' jest.mock('lib/realtime') -initializeRealtime.mockResolvedValue(Promise.resolve()) const { init } = stack @@ -30,6 +29,15 @@ describe('stack client', () => { await init(params) } + beforeEach(() => { + isLogged = undefined + isPublic = undefined + initializeRealtime.mockReset().mockImplementation(() => { + terminateRealtime = jest.fn() + return terminateRealtime + }) + }) + afterAll(() => { jest.restoreAllMocks() }) @@ -49,5 +57,13 @@ describe('stack client', () => { expect(initializeRealtime).toHaveBeenCalled() expect(initializeRealtime.mock.calls[0][0].cozyClient).toBe(cozyClient) }) + + it('should terminate realtime if the user logs out', async () => { + isLogged = true + await setup() + expect(terminateRealtime).not.toHaveBeenCalled() + cozyClient.emit('logout') + expect(terminateRealtime).toHaveBeenCalled() + }) }) })