From 7920364d6b6ac29e1b7fdbb38c8a9fe22eec61de Mon Sep 17 00:00:00 2001 From: Michael Mok Date: Tue, 5 Apr 2022 13:13:52 +0200 Subject: [PATCH] feat: export initialized socket client (#4304) --- client-src/socket.js | 6 +++++- test/client/socket-helper.test.js | 17 ++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/client-src/socket.js b/client-src/socket.js index 4b913e4c69..6fb023e32a 100644 --- a/client-src/socket.js +++ b/client-src/socket.js @@ -16,7 +16,11 @@ const Client = let retries = 0; let maxRetries = 10; -let client = null; + +// Initialized client is exported so external consumers can utilize the same instance +// It is mutable to enforce singleton +// eslint-disable-next-line import/no-mutable-exports +export let client = null; /** * @param {string} url diff --git a/test/client/socket-helper.test.js b/test/client/socket-helper.test.js index 4951949d6c..17077de0a8 100644 --- a/test/client/socket-helper.test.js +++ b/test/client/socket-helper.test.js @@ -5,7 +5,7 @@ "use strict"; describe("socket", () => { - afterEach(() => { + beforeEach(() => { jest.resetAllMocks(); jest.resetModules(); }); @@ -77,4 +77,19 @@ describe("socket", () => { expect(mockClientInstance.onMessage.mock.calls).toMatchSnapshot(); expect(mockHandler.mock.calls).toMatchSnapshot(); }); + + it("should export initialized client", () => { + const socket = require("../../client/socket").default; + + const nonInitializedInstance = require("../../client/socket").client; + expect(nonInitializedInstance).toBe(null); + + socket("my.url", {}); + + const initializedInstance = require("../../client/socket").client; + expect(initializedInstance).not.toBe(null); + expect(typeof initializedInstance.onClose).toBe("function"); + expect(typeof initializedInstance.onMessage).toBe("function"); + expect(typeof initializedInstance.onOpen).toBe("function"); + }); });