From 84d612964bd42be8b2c93a94127756f60fb0c1e1 Mon Sep 17 00:00:00 2001 From: Omridan159 Date: Thu, 29 Feb 2024 13:22:22 +0000 Subject: [PATCH] chore: fix unit tests --- .../ChannelManager/clean.test.ts | 20 ++--- .../generateChannelIdConnect.test.ts | 19 +++-- .../connectToChannel.test.ts | 23 +++--- .../ConnectionManager/connectToChannel.ts | 2 +- .../ConnectionManager/disconnect.test.ts | 12 ++- .../handleAuthorization.test.ts | 18 ++--- .../originatorSessionConnect.test.ts | 15 ++-- .../ConnectionManager/resume.test.ts | 29 ++++--- .../handleChannelCreatedEvent.test.ts | 18 ++--- .../handleClientsConnectedEvent.test.ts | 22 ++---- .../handleClientsDisconnectedEvent.test.ts | 10 ++- .../handleClientsWaitingEvent.test.ts | 14 +++- .../handleKeysExchangedEvent.test.ts | 9 ++- .../handleSocketDisconnectedEvent.test.ts | 20 ++--- .../handleSocketReconnectEvent.test.ts | 11 +-- .../onCommunicationLayerMessage.test.ts | 13 +++- .../MessageHandlers/sendMessage.test.ts | 13 ++-- .../StateManger/setLastActiveDate.test.ts | 14 ++-- .../StorageManager/testStorage.test.ts | 15 ++-- .../ChannelManager/createChannel.test.ts | 12 +-- .../checkFocusAndReconnect.test.ts | 10 +-- .../connectToChannel.test.ts | 14 ++-- .../ConnectionManager/disconnect.test.ts | 14 ++-- .../ConnectionManager/pause.test.ts | 14 ++-- .../ConnectionManager/ping.test.ts | 13 ++-- .../ConnectionManager/reconnectSocket.test.ts | 14 ++-- .../ConnectionManager/resume.test.ts | 23 +++--- .../handleChannelCreated.test.ts | 15 ++-- .../handleClientsConnected.test.ts | 18 ++--- .../handleClientsWaitingToJoin.test.ts | 14 ++-- .../EventListeners/handleDisconnect.test.ts | 14 ++-- .../EventListeners/handleKeyInfo.test.ts | 14 ++-- .../handleKeysExchanged.test.ts | 12 ++- .../EventListeners/handleMessage.test.ts | 39 ++++------ .../EventListeners/handlePing.test.ts | 32 ++------ .../EventListeners/handleReconnect.test.ts | 32 ++------ .../handleReconnectError.test.ts | 30 ++------ .../handleReconnectFailed.test.ts | 20 ++--- .../EventListeners/handleSocketError.test.ts | 21 ++---- .../handlesClientsDisconnected.test.ts | 12 +-- .../KeysManager/handleKeyHandshake.test.ts | 14 ++-- .../KeysManager/resetKeys.test.ts | 14 ++-- .../KeysManager/validateKeyExchange.test.ts | 10 ++- .../encryptAndSendMessage.test.ts | 22 +++++- .../MessageHandlers/handleRpcReplies.test.ts | 15 ++-- .../useHandleChainChangedEvent.test.tsx | 37 +++------ .../useHandleConnectEvent.test.tsx | 33 ++------ .../useHandleDisconnectEvent.test.tsx | 26 ++----- .../useHandleInitializedEvent.test.tsx | 26 ++----- .../useHandleOnConnectingEvent.test.tsx | 27 ++----- .../useHandleProviderEvent.test.tsx | 26 ++----- .../useHandleSDKStatusEvent.test.tsx | 26 ++----- .../sdk-react/src/MetaMaskProvider.spec.tsx | 14 ++-- ...moteCommunicationPostMessageStream.test.ts | 2 - .../getPostMessageStream.test.ts | 1 - packages/sdk/src/provider/SDKProvider.test.ts | 5 -- .../provider/wrapExtensionProvider.test.ts | 12 ++- packages/sdk/src/services/Analytics.test.ts | 23 ++---- packages/sdk/src/services/Ethereum.test.ts | 2 - .../checkInstallation.test.ts | 12 ++- .../redirectToProperInstall.test.ts | 8 +- .../startDesktopOnboarding.test.ts | 26 ++----- .../MetaMaskInstaller/startInstaller.test.ts | 11 ++- .../ConnectionManager/connect.test.ts | 15 ++-- .../ConnectionManager/resume.test.ts | 8 +- .../ConnectionManager/terminate.test.ts | 15 ++-- .../InitializerManager/setupAnalytics.test.ts | 3 +- .../connectWithExtensionProvider.test.ts | 22 +++--- .../connectWithExtensionProvider.ts | 2 +- .../isMetaMaskInstalled.test.ts | 32 +++----- .../PlatfformManager/openDeeplink.test.ts | 69 ++++++++++------- .../onMessage.test.ts | 10 +-- .../write.test.ts | 75 +++---------------- .../write.ts | 4 +- .../initializeConnector.test.ts | 11 +-- .../handleDisconnect.test.ts | 13 +--- .../ConnectionManager/startConnection.test.ts | 7 +- .../EventListeners/setupListeners.test.ts | 5 ++ .../EventListeners/setupListeners.ts | 4 + .../ModalManager/showInstallModal.test.ts | 27 +------ .../ChainManager/handleChainChanged.test.ts | 9 +-- .../handleDisconnect.test.ts | 33 +++----- .../ConnectionManager/handleDisconnect.ts | 2 +- .../initializeState.test.ts | 12 +-- .../initializeStateAsync.test.ts | 27 +++---- .../InstallModal/InstallModal-nodejs.test.ts | 22 +++--- .../InstallModal/InstallModal-nonweb.test.ts | 9 ++- .../ui/InstallModal/InstallModal-web.test.ts | 16 ++-- .../InstallModal/pendingModal-nodejs.test.ts | 35 ++++----- 89 files changed, 604 insertions(+), 959 deletions(-) diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/ChannelManager/clean.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/ChannelManager/clean.test.ts index faaab5a0d..d7385166d 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/ChannelManager/clean.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/ChannelManager/clean.test.ts @@ -1,7 +1,9 @@ import { RemoteCommunicationState } from '../../../RemoteCommunication'; +import * as loggerModule from '../../../utils/logger'; import { clean } from './clean'; describe('clean', () => { + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); let state: RemoteCommunicationState; beforeEach(() => { @@ -27,23 +29,11 @@ describe('clean', () => { expect(state.originatorConnectStarted).toBe(false); }); - it('should log a debug message if debug is true', () => { - jest.spyOn(console, 'debug').mockImplementation(); - - state.debug = true; - + it('should log a debug message', () => { clean(state); - expect(console.debug).toHaveBeenCalledWith( - 'RemoteCommunication::test::clean()', + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: clean()] context=test', ); }); - - it('should not log a debug message if debug is false', () => { - jest.spyOn(console, 'debug').mockImplementation(); - - clean(state); - - expect(console.debug).not.toHaveBeenCalled(); - }); }); diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/ChannelManager/generateChannelIdConnect.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/ChannelManager/generateChannelIdConnect.test.ts index b40ef6e41..ae0818379 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/ChannelManager/generateChannelIdConnect.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/ChannelManager/generateChannelIdConnect.test.ts @@ -2,6 +2,7 @@ import { RemoteCommunicationState } from '../../../RemoteCommunication'; import { CommunicationLayer } from '../../../types/CommunicationLayer'; import { StorageManager } from '../../../types/StorageManager'; +import * as loggerModule from '../../../utils/logger'; import { generateChannelIdConnect } from './generateChannelIdConnect'; import { clean } from './clean'; @@ -10,6 +11,8 @@ jest.mock('./clean'); describe('generateChannelIdConnect', () => { let state: RemoteCommunicationState; + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); + const mockClean = clean as jest.MockedFunction; beforeEach(() => { @@ -117,20 +120,16 @@ describe('generateChannelIdConnect', () => { ); }); - it('should log debug messages if debug is enabled', () => { - jest.spyOn(console, 'debug').mockImplementation(); - - state.debug = true; - + it('should log debug messages', () => { generateChannelIdConnect(state); - expect(console.debug).toHaveBeenCalledWith( - `RemoteCommunication::generateChannelId()`, + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: generateChannelId()]', ); - expect(console.debug).toHaveBeenCalledWith( - `RemoteCommunication::generateChannelId() channel created`, - expect.anything(), + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: generateChannelId()] channel created', + { channelId: 'mockChannelId', pubKey: 'mockPublicKey' }, ); }); diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/connectToChannel.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/connectToChannel.test.ts index 78fd1ff9b..fd54d5633 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/connectToChannel.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/connectToChannel.test.ts @@ -2,11 +2,14 @@ import { v4 as uuid } from 'uuid'; import { RemoteCommunicationState } from '../../../RemoteCommunication'; import { CommunicationLayer } from '../../../types/CommunicationLayer'; import { StorageManager } from '../../../types/StorageManager'; +import * as loggerModule from '../../../utils/logger'; import { connectToChannel } from './connectToChannel'; describe('connectToChannel', () => { let state: RemoteCommunicationState; + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); + beforeEach(() => { jest.clearAllMocks(); @@ -32,19 +35,16 @@ describe('connectToChannel', () => { it('should debug log if the channel is already connected', () => { const channelId = uuid(); + state.communicationLayer = { isConnected: jest.fn(() => true), } as unknown as CommunicationLayer; - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - connectToChannel({ channelId, state }); - expect(consoleDebugSpy).toHaveBeenCalledWith( - `RemoteCommunication::TestContext::connectToChannel() already connected - interrup connection.`, + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: connectToChannel()] context=TestContext already connected - interrupt connection.', ); - - consoleDebugSpy.mockRestore(); }); it('should connect to a valid channel', () => { @@ -100,19 +100,14 @@ describe('connectToChannel', () => { }); }); - it('should debug log a valid channelId if debug is enabled', () => { + it('should debug log a valid channelId', () => { const channelId = uuid(); - state.debug = true; - - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); connectToChannel({ channelId, state }); - expect(consoleDebugSpy).toHaveBeenCalledWith( - `RemoteCommunication::${state.context}::connectToChannel() channelId=${channelId}`, + expect(spyLogger).toHaveBeenCalledWith( + `[RemoteCommunication: connectToChannel()] context=TestContext channelId=${channelId}`, ); - - consoleDebugSpy.mockRestore(); }); it('should set the new channelId in the state', () => { diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/connectToChannel.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/connectToChannel.ts index 887bdc7b6..20e359102 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/connectToChannel.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/connectToChannel.ts @@ -35,7 +35,7 @@ export function connectToChannel({ if (state.communicationLayer?.isConnected()) { // Adding a check on previous connection to prevent reconnecting during dev when HMR is enabled loggerRemoteLayer( - `[RemoteCommunication: connectToChannel()] context=${state.context} already connected - interrup connection.`, + `[RemoteCommunication: connectToChannel()] context=${state.context} already connected - interrupt connection.`, ); return; } diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/disconnect.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/disconnect.test.ts index 9614bed46..8d8e06af0 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/disconnect.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/disconnect.test.ts @@ -3,12 +3,15 @@ import { ConnectionStatus } from '../../../types/ConnectionStatus'; import { CommunicationLayer } from '../../../types/CommunicationLayer'; import { StorageManager } from '../../../types/StorageManager'; import { MessageType } from '../../../types/MessageType'; +import * as loggerModule from '../../../utils/logger'; import { disconnect } from './disconnect'; describe('disconnect', () => { let instance: RemoteCommunication; const mockSetConnectionStatus = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); + beforeEach(() => { jest.clearAllMocks(); @@ -134,17 +137,12 @@ describe('disconnect', () => { }); it('should log debug information if debug is enabled', () => { - instance.state.debug = true; - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - disconnect({ instance }); - expect(consoleDebugSpy).toHaveBeenCalledWith( - `RemoteCommunication::disconnect() channel=${instance.state.channelId}`, + expect(spyLogger).toHaveBeenCalledWith( + `[RemoteCommunication: disconnect()] channel=${instance.state.channelId}`, undefined, ); - - consoleDebugSpy.mockRestore(); }); it('should reset originatorConnectStarted on termination', () => { diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/handleAuthorization.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/handleAuthorization.test.ts index 37442e56e..c90f42819 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/handleAuthorization.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/handleAuthorization.test.ts @@ -2,12 +2,15 @@ import { RemoteCommunication } from '../../../RemoteCommunication'; import { CommunicationLayerMessage } from '../../../types/CommunicationLayerMessage'; import { EventType } from '../../../types/EventType'; +import * as loggerModule from '../../../utils/logger'; import { handleAuthorization } from './handleAuthorization'; describe('handleAuthorization', () => { let instance: RemoteCommunication; let message: CommunicationLayerMessage; + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); + const mockOnce = jest.fn(); const mockSendMessage = jest.fn(); @@ -85,19 +88,16 @@ describe('handleAuthorization', () => { ); }); - it('should log debug information if debug is enabled', async () => { - instance.state.debug = true; - const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(); - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - + it('should log debug information', async () => { await handleAuthorization(instance, message); - expect(consoleLogSpy).toHaveBeenCalledWith( - `RemoteCommunication::${instance.state.context}::sendMessage::handleAuthorization ready=${instance.state.ready} authorized=${instance.state.authorized} method=${message.method}`, + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: handleAuthorization()] context=testContext ready=true authorized=false method=sampleMethod', ); - consoleLogSpy.mockRestore(); - consoleDebugSpy.mockRestore(); + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: handleAuthorization()] context=testContext AFTER SKIP / AUTHORIZED -- sending pending message', + ); }); it('should correctly handle wallet versions like 7.10 vs 7.9', async () => { diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/originatorSessionConnect.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/originatorSessionConnect.test.ts index 3531d1fca..a6e307f2c 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/originatorSessionConnect.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/originatorSessionConnect.test.ts @@ -1,8 +1,11 @@ import { RemoteCommunication } from '../../../RemoteCommunication'; +import * as loggerModule from '../../../utils/logger'; import { originatorSessionConnect } from './originatorSessionConnect'; describe('originatorSessionConnect', () => { let instance: RemoteCommunication; + + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); const mockIsConnected = jest.fn(); const mockGetPersistedChannelConfig = jest.fn(); const mockConnectToChannel = jest.fn(); @@ -31,8 +34,8 @@ describe('originatorSessionConnect', () => { delete instance.state.storageManager; const result = await originatorSessionConnect(instance); expect(result).toBeUndefined(); - expect(console.debug).toHaveBeenCalledWith( - 'RemoteCommunication::connect() no storage manager defined - skip', + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: originatorSessionConnect()] no storage manager defined - skip', ); }); @@ -40,8 +43,8 @@ describe('originatorSessionConnect', () => { mockIsConnected.mockReturnValueOnce(true); const result = await originatorSessionConnect(instance); expect(result).toBeUndefined(); - expect(console.debug).toHaveBeenCalledWith( - 'RemoteCommunication::connect() socket already connected - skip', + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: originatorSessionConnect()] socket already connected - skip', ); }); @@ -69,8 +72,8 @@ describe('originatorSessionConnect', () => { const result = await originatorSessionConnect(instance); expect(result).toBeUndefined(); - expect(console.log).toHaveBeenCalledWith( - 'RemoteCommunication::autoConnect Session has expired', + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: autoConnect()] Session has expired', ); }); diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/resume.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/resume.test.ts index 39d676b52..ebc4037ac 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/resume.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/ConnectionManager/resume.test.ts @@ -1,9 +1,12 @@ import { RemoteCommunication } from '../../../RemoteCommunication'; import { ConnectionStatus } from '../../../types/ConnectionStatus'; +import * as loggerModule from '../../../utils/logger'; import { resume } from './resume'; describe('resume', () => { let instance: RemoteCommunication; + + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); const mockResume = jest.fn(); const mockSetConnectionStatus = jest.fn(); @@ -24,19 +27,13 @@ describe('resume', () => { } as unknown as RemoteCommunication; }); - it('should log channel being resumed when debug is true', () => { + it('should log channel info', () => { resume(instance); - expect(console.debug).toHaveBeenCalledWith( - `RemoteCommunication::resume() channel=testChannel`, + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: resume()] channel=testChannel', ); }); - it('should not log when debug is false', () => { - instance.state.debug = false; - resume(instance); - expect(console.debug).not.toHaveBeenCalled(); - }); - it('should call resume on the communication layer', () => { resume(instance); expect(mockResume).toHaveBeenCalledTimes(1); @@ -56,8 +53,8 @@ describe('resume', () => { resume(instance); }).not.toThrow(); - expect(console.debug).toHaveBeenCalledWith( - `RemoteCommunication::resume() channel=testChannel`, + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: resume()] channel=testChannel', ); }); @@ -74,17 +71,17 @@ describe('resume', () => { instance.state.channelId = undefined; resume(instance); - expect(console.debug).toHaveBeenCalledWith( - `RemoteCommunication::resume() channel=undefined`, + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: resume()] channel=undefined', ); }); - it('should handle when channelId is undefined', () => { + it('should log debug info when channelId is undefined', () => { instance.state.channelId = undefined; resume(instance); - expect(console.debug).toHaveBeenCalledWith( - `RemoteCommunication::resume() channel=undefined`, + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: resume()] channel=undefined', ); }); }); diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleChannelCreatedEvent.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleChannelCreatedEvent.test.ts index 030622cb7..ff1fe5783 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleChannelCreatedEvent.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleChannelCreatedEvent.test.ts @@ -1,12 +1,13 @@ import { RemoteCommunication } from '../../../RemoteCommunication'; import { EventType } from '../../../types/EventType'; +import * as loggerModule from '../../../utils/logger'; import { handleChannelCreatedEvent } from './handleChannelCreatedEvent'; describe('handleChannelCreatedEvent', () => { let instance: RemoteCommunication; - const mockEmit = jest.fn(); - jest.spyOn(console, 'debug').mockImplementation(); + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); + const mockEmit = jest.fn(); beforeEach(() => { jest.clearAllMocks(); @@ -28,17 +29,10 @@ describe('handleChannelCreatedEvent', () => { const channelId = 'sampleChannelId'; const handler = handleChannelCreatedEvent(instance); handler(channelId); - expect(console.debug).toHaveBeenCalledWith( - `RemoteCommunication::testContext::on 'channel_created' channelId=${channelId}`, - ); - }); - it('should not log the event details if debugging is disabled', () => { - instance.state.debug = false; - const channelId = 'sampleChannelId'; - const handler = handleChannelCreatedEvent(instance); - handler(channelId); - expect(console.debug).not.toHaveBeenCalled(); + expect(spyLogger).toHaveBeenCalledWith( + "[RemoteCommunication: handleChannelCreatedEvent()] context=testContext on 'channel_created' channelId=sampleChannelId", + ); }); it('should emit CHANNEL_CREATED event with the channel ID', () => { diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleClientsConnectedEvent.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleClientsConnectedEvent.test.ts index fb525c903..b041be330 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleClientsConnectedEvent.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleClientsConnectedEvent.test.ts @@ -3,6 +3,7 @@ import { CommunicationLayerPreference } from '../../../types/CommunicationLayerP import { EventType } from '../../../types/EventType'; import { SendAnalytics } from '../../../Analytics'; import packageJson from '../../../../package.json'; +import * as loggerModule from '../../../utils/logger'; import { handleClientsConnectedEvent } from './handleClientsConnectedEvent'; jest.mock('../../../Analytics', () => ({ @@ -14,8 +15,8 @@ describe('handleClientsConnectedEvent', () => { const mockEmit = jest.fn(); const mockGetKeyInfo = jest.fn(); - // Mock console.debug and console.error - jest.spyOn(console, 'debug').mockImplementation(); + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); + jest.spyOn(console, 'error').mockImplementation(); beforeEach(() => { @@ -43,14 +44,15 @@ describe('handleClientsConnectedEvent', () => { }); }); - it('should log the event details if debugging is enabled', () => { + it('should log the event details', () => { const handler = handleClientsConnectedEvent( instance, CommunicationLayerPreference.SOCKET, ); handler(); - expect(console.debug).toHaveBeenCalledWith( - `RemoteCommunication::on 'clients_connected' channel=testChannel keysExchanged=true`, + + expect(spyLogger).toHaveBeenCalledWith( + "[RemoteCommunication: handleClientsConnectedEvent()] on 'clients_connected' channel=testChannel keysExchanged=true", ); }); @@ -105,16 +107,6 @@ describe('handleClientsConnectedEvent', () => { ); }); - it('should not log event details if debugging is disabled', () => { - instance.state.debug = false; - const handler = handleClientsConnectedEvent( - instance, - CommunicationLayerPreference.SOCKET, - ); - handler(); - expect(console.debug).not.toHaveBeenCalled(); - }); - it('should not send analytics data if analytics tracking is disabled', async () => { instance.state.analytics = false; const handler = handleClientsConnectedEvent( diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleClientsDisconnectedEvent.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleClientsDisconnectedEvent.test.ts index 7560ef916..55c8b1f19 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleClientsDisconnectedEvent.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleClientsDisconnectedEvent.test.ts @@ -2,6 +2,7 @@ import { SendAnalytics } from '../../../Analytics'; import { RemoteCommunication } from '../../../RemoteCommunication'; import { CommunicationLayerPreference } from '../../../types/CommunicationLayerPreference'; import { EventType } from '../../../types/EventType'; +import * as loggerModule from '../../../utils/logger'; import { handleClientsConnectedEvent } from './handleClientsConnectedEvent'; jest.mock('../../../../package.json', () => ({ @@ -14,6 +15,9 @@ jest.mock('../../../Analytics', () => ({ describe('handleClientsConnectedEvent', () => { let instance: RemoteCommunication; + + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); + const mockEmit = jest.fn(); const mockGetKeyInfo = jest.fn(); @@ -43,14 +47,14 @@ describe('handleClientsConnectedEvent', () => { }); }); - it('should log event details if debug is enabled', () => { + it('should log event details', () => { const handler = handleClientsConnectedEvent( instance, CommunicationLayerPreference.SOCKET, ); handler(); - expect(console.debug).toHaveBeenCalledWith( - `RemoteCommunication::on 'clients_connected' channel=testChannel keysExchanged=true`, + expect(spyLogger).toHaveBeenCalledWith( + "[RemoteCommunication: handleClientsConnectedEvent()] on 'clients_connected' channel=testChannel keysExchanged=true", ); }); diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleClientsWaitingEvent.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleClientsWaitingEvent.test.ts index e18f2909b..dccfc6858 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleClientsWaitingEvent.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleClientsWaitingEvent.test.ts @@ -2,12 +2,15 @@ import { RemoteCommunication } from '../../../RemoteCommunication'; import { ConnectionStatus } from '../../../types/ConnectionStatus'; import { EventType } from '../../../types/EventType'; +import * as loggerModule from '../../../utils/logger'; import { handleClientsWaitingEvent } from './handleClientsWaitingEvent'; jest.useFakeTimers(); describe('handleClientsWaitingEvent', () => { let instance: RemoteCommunication; + + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); const mockEmit = jest.fn(); const mockSetConnectionStatus = jest.fn(); @@ -38,11 +41,16 @@ describe('handleClientsWaitingEvent', () => { jest.useRealTimers(); }); - it('should log event details if debug is enabled', () => { + it('should log event details', () => { const handler = handleClientsWaitingEvent(instance); handler(5); - expect(console.debug).toHaveBeenCalledWith( - `RemoteCommunication::mockContext::on 'clients_waiting' numberUsers=5 ready=false autoStarted=true`, + expect(spyLogger).toHaveBeenCalledWith( + "[RemoteCommunication: handleClientsWaitingEvent()] context=mockContext on 'clients_waiting' numberUsers=5 ready=false autoStarted=true", + ); + + expect(spyLogger).toHaveBeenCalledWith( + "[RemoteCommunication: handleClientsWaitingEvent()] on 'clients_waiting' watch autoStarted=true timeout", + { timeout: 4000 }, ); }); diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleKeysExchangedEvent.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleKeysExchangedEvent.test.ts index 87fafc002..5e4b0b41f 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleKeysExchangedEvent.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleKeysExchangedEvent.test.ts @@ -5,6 +5,7 @@ import { ConnectionStatus } from '../../../types/ConnectionStatus'; import { MessageType } from '../../../types/MessageType'; import { OriginatorInfo } from '../../../types/OriginatorInfo'; import { setLastActiveDate } from '../StateManger'; +import * as loggerModule from '../../../utils/logger'; import { handleKeysExchangedEvent } from './handleKeysExchangedEvent'; jest.mock('../../../Analytics', () => { @@ -17,10 +18,11 @@ jest.mock('../StateManger'); describe('handleKeysExchangedEvent', () => { let instance: RemoteCommunication; + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); + const mockSetConnectionStatus = jest.fn(); const mockSendMessage = jest.fn(); - jest.spyOn(console, 'debug').mockImplementation(); jest.spyOn(console, 'error').mockImplementation(); beforeEach(() => { @@ -44,7 +46,7 @@ describe('handleKeysExchangedEvent', () => { } as unknown as RemoteCommunication; }); - it('should log diagnostic information when debug is enabled', () => { + it('should log diagnostic information', () => { const handler = handleKeysExchangedEvent( instance, CommunicationLayerPreference.SOCKET, @@ -54,7 +56,8 @@ describe('handleKeysExchangedEvent', () => { originatorInfo: {} as OriginatorInfo, originator: {} as OriginatorInfo, }); - expect(console.debug).toHaveBeenCalled(); + + expect(spyLogger).toHaveBeenCalled(); }); it('should update the instance connection status to LINKED', () => { diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleSocketDisconnectedEvent.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleSocketDisconnectedEvent.test.ts index 4fcef3387..1a41de9e5 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleSocketDisconnectedEvent.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleSocketDisconnectedEvent.test.ts @@ -1,16 +1,18 @@ import { RemoteCommunication } from '../../../RemoteCommunication'; +import * as loggerModule from '../../../utils/logger'; import { handleSocketDisconnectedEvent } from './handleSocketDisconnectedEvent'; describe('handleSocketDisconnectedEvent', () => { let instance: RemoteCommunication; + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); + beforeEach(() => { jest.clearAllMocks(); instance = { state: { ready: true, - debug: false, }, } as unknown as RemoteCommunication; }); @@ -22,24 +24,12 @@ describe('handleSocketDisconnectedEvent', () => { }); it('should log a debug message when debug is true', () => { - instance.state.debug = true; - const mockConsoleDebug = jest.spyOn(console, 'debug').mockImplementation(); const handler = handleSocketDisconnectedEvent(instance); handler(); - expect(mockConsoleDebug).toHaveBeenCalledWith( - `RemoteCommunication::on 'socket_Disconnected' set ready to false`, + expect(spyLogger).toHaveBeenCalledWith( + "[RemoteCommunication: handleSocketDisconnectedEvent()] on 'socket_Disconnected' set ready to false", ); - mockConsoleDebug.mockRestore(); - }); - - it('should not log a debug message when debug is false', () => { - instance.state.debug = false; - const mockConsoleDebug = jest.spyOn(console, 'debug').mockImplementation(); - const handler = handleSocketDisconnectedEvent(instance); - handler(); - expect(mockConsoleDebug).not.toHaveBeenCalled(); - mockConsoleDebug.mockRestore(); }); }); diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleSocketReconnectEvent.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleSocketReconnectEvent.test.ts index fed133fd6..4653a1820 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleSocketReconnectEvent.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/EventListeners/handleSocketReconnectEvent.test.ts @@ -1,11 +1,14 @@ import { RemoteCommunication } from '../../../RemoteCommunication'; import { clean } from '../ChannelManager'; +import * as loggerModule from '../../../utils/logger'; import { handleSocketReconnectEvent } from './handleSocketReconnectEvent'; jest.mock('../ChannelManager'); describe('handleSocketReconnectEvent', () => { let instance: RemoteCommunication; + + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); const mockClean = clean as jest.MockedFunction; beforeEach(() => { @@ -33,13 +36,11 @@ describe('handleSocketReconnectEvent', () => { }); it('should log a debug message when debug is true', () => { - instance.state.debug = true; - const mockConsoleDebug = jest.spyOn(console, 'debug').mockImplementation(); const handler = handleSocketReconnectEvent(instance); handler(); - expect(mockConsoleDebug).toHaveBeenCalledWith( - `RemoteCommunication::on 'socket_reconnect' -- reset key exchange status / set ready to false`, + + expect(spyLogger).toHaveBeenCalledWith( + "[RemoteCommunication: handleSocketReconnectEvent()] on 'socket_reconnect' -- reset key exchange status / set ready to false", ); - mockConsoleDebug.mockRestore(); }); }); diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/MessageHandlers/onCommunicationLayerMessage.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/MessageHandlers/onCommunicationLayerMessage.test.ts index b79cf1f12..4ed98a80d 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/MessageHandlers/onCommunicationLayerMessage.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/MessageHandlers/onCommunicationLayerMessage.test.ts @@ -2,6 +2,7 @@ import { RemoteCommunication } from '../../../RemoteCommunication'; import { CommunicationLayerMessage } from '../../../types/CommunicationLayerMessage'; import { MessageType } from '../../../types/MessageType'; import { EventType } from '../../../types/EventType'; +import * as loggerModule from '../../../utils/logger'; import { onCommunicationLayerMessage } from './onCommunicationLayerMessage'; import { handleOriginatorInfoMessage } from './handleOriginatorInfoMessage'; import { handleAuthorizedMessage } from './handleAuthorizedMessage'; @@ -43,6 +44,8 @@ describe('onCommunicationLayerMessage', () => { let instance: RemoteCommunication; let message: CommunicationLayerMessage; + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); + const mockHandleOriginatorInfoMessage = handleOriginatorInfoMessage as jest.MockedFunction< typeof handleOriginatorInfoMessage @@ -63,12 +66,14 @@ describe('onCommunicationLayerMessage', () => { }); it('should log the message if debug mode is enabled', () => { - instance.state.debug = true; - const consoleDebugSpy = jest.spyOn(console, 'debug'); message = { type: MessageType.READY }; // Any arbitrary message type + onCommunicationLayerMessage(message, instance); - expect(consoleDebugSpy).toHaveBeenCalled(); - consoleDebugSpy.mockRestore(); + + expect(spyLogger).toHaveBeenCalledWith( + "[RemoteCommunication: onCommunicationLayerMessage()] context=test-context on 'message' typeof=object", + message, + ); }); it('should set the ready status to true', () => { diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/MessageHandlers/sendMessage.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/MessageHandlers/sendMessage.test.ts index 66be67c1c..df8f260a5 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/MessageHandlers/sendMessage.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/MessageHandlers/sendMessage.test.ts @@ -3,6 +3,7 @@ import { CommunicationLayerMessage } from '../../../types/CommunicationLayerMess import { EventType } from '../../../types/EventType'; import { MessageType } from '../../../types/MessageType'; import { handleAuthorization } from '../ConnectionManager'; +import * as loggerModule from '../../../utils/logger'; import { sendMessage } from './sendMessage'; jest.mock('../ConnectionManager'); @@ -11,6 +12,7 @@ describe('sendMessage', () => { let instance: RemoteCommunication; let message: CommunicationLayerMessage; + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); const mockHandleAuthorization = handleAuthorization as jest.Mock; const mockOnce = jest.fn( (_: EventType, callback: (data: unknown) => void) => { @@ -44,12 +46,13 @@ describe('sendMessage', () => { } as unknown as CommunicationLayerMessage; }); - it('should log if debug mode is enabled', async () => { - instance.state.debug = true; - const consoleLogSpy = jest.spyOn(console, 'log'); + it('should log debug info', async () => { await sendMessage(instance, message); - expect(consoleLogSpy).toHaveBeenCalled(); - consoleLogSpy.mockRestore(); + + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: sendMessage()] context=test-context paused=false ready=true authorized=true socket=true clientsConnected=true status=connected', + message, + ); }); it('should wait for CLIENTS_READY event if conditions are not favorable', async () => { diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/StateManger/setLastActiveDate.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/StateManger/setLastActiveDate.test.ts index 7ee5d3885..e1e31e363 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/StateManger/setLastActiveDate.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/StateManger/setLastActiveDate.test.ts @@ -1,11 +1,14 @@ import { RemoteCommunication } from '../../../RemoteCommunication'; import { ChannelConfig } from '../../../types/ChannelConfig'; +import * as loggerModule from '../../../utils/logger'; import { setLastActiveDate } from './setLastActiveDate'; describe('setLastActiveDate', () => { let instance: RemoteCommunication; let lastActiveDate: Date; + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); + beforeEach(() => { jest.clearAllMocks(); @@ -25,18 +28,13 @@ describe('setLastActiveDate', () => { lastActiveDate = new Date('2023-01-01T12:00:00Z'); }); - it('should log if debug mode is enabled', () => { - instance.state.debug = true; - const consoleDebugSpy = jest.spyOn(console, 'debug'); - + it('should log debug info', () => { setLastActiveDate(instance, lastActiveDate); - expect(consoleDebugSpy).toHaveBeenCalledWith( - `RemoteCommunication::setLastActiveDate() channel=${instance.state.channelId}`, + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: setLastActiveDate()] channel=test-channel-id', lastActiveDate, ); - - consoleDebugSpy.mockRestore(); }); it('should set the lastActive attribute correctly', () => { diff --git a/packages/sdk-communication-layer/src/services/RemoteCommunication/StorageManager/testStorage.test.ts b/packages/sdk-communication-layer/src/services/RemoteCommunication/StorageManager/testStorage.test.ts index 411cc0229..0ec2d84e1 100644 --- a/packages/sdk-communication-layer/src/services/RemoteCommunication/StorageManager/testStorage.test.ts +++ b/packages/sdk-communication-layer/src/services/RemoteCommunication/StorageManager/testStorage.test.ts @@ -1,9 +1,12 @@ import { RemoteCommunicationState } from '../../../RemoteCommunication'; +import * as loggerModule from '../../../utils/logger'; import { testStorage } from './testStorage'; describe('testStorage', () => { let state: RemoteCommunicationState; + const spyLogger = jest.spyOn(loggerModule, 'loggerRemoteLayer'); + beforeEach(() => { jest.clearAllMocks(); @@ -24,28 +27,24 @@ describe('testStorage', () => { }); it('should log the result', async () => { - const consoleDebugSpy = jest.spyOn(console, 'debug'); await testStorage(state); - expect(consoleDebugSpy).toHaveBeenCalledWith( - 'RemoteCommunication.testStorage() res', + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: testStorage()] res', expect.any(Object), ); - consoleDebugSpy.mockRestore(); }); it('should handle case when storageManager is not defined', async () => { state.storageManager = undefined; - const consoleDebugSpy = jest.spyOn(console, 'debug'); const res = await testStorage(state); expect(res).toBeUndefined(); - expect(consoleDebugSpy).toHaveBeenCalledWith( - 'RemoteCommunication.testStorage() res', + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteCommunication: testStorage()] res', undefined, ); - consoleDebugSpy.mockRestore(); }); }); diff --git a/packages/sdk-communication-layer/src/services/SocketService/ChannelManager/createChannel.test.ts b/packages/sdk-communication-layer/src/services/SocketService/ChannelManager/createChannel.test.ts index b87086a01..31fd06b73 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/ChannelManager/createChannel.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/ChannelManager/createChannel.test.ts @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/no-non-null-assertion */ import { SocketService } from '../../../SocketService'; +import * as loggerModule from '../../../utils/logger'; import { createChannel } from './createChannel'; import { setupChannelListeners } from './setupChannelListeners'; @@ -12,6 +13,8 @@ const mockGetMyPublicKey = jest.fn(); describe('createChannel', () => { let instance: SocketService; + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); + beforeEach(() => { jest.clearAllMocks(); @@ -88,14 +91,11 @@ describe('createChannel', () => { expect(result.pubKey).toBe(''); }); - it('should log the creation process if debug is true', () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; + it('should log debug info', () => { createChannel(instance); - expect(consoleDebugSpy).toHaveBeenCalledWith( - 'SocketService::testContext::createChannel()', + expect(spyLogger).toHaveBeenCalledWith( + `[SocketService: createChannel()] context=${instance.state.context}`, ); - consoleDebugSpy.mockRestore(); }); }); diff --git a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/checkFocusAndReconnect.test.ts b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/checkFocusAndReconnect.test.ts index b6a3a801f..fe8792fd8 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/checkFocusAndReconnect.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/checkFocusAndReconnect.test.ts @@ -4,7 +4,7 @@ import { reconnectSocket } from './reconnectSocket'; jest.mock('./reconnectSocket'); -const mockHasFocus = jest.fn(() => false); +const mockHasFocus = jest.fn(); const mockAddEventListener = jest.fn(); describe('checkFocusAndReconnect', () => { @@ -13,6 +13,8 @@ describe('checkFocusAndReconnect', () => { beforeEach(() => { jest.clearAllMocks(); + mockHasFocus.mockReturnValue(false); + global.document = { hasFocus: mockHasFocus, } as unknown as Document; @@ -22,9 +24,7 @@ describe('checkFocusAndReconnect', () => { } as unknown as Window & typeof globalThis; instance = { - state: { - debug: false, - }, + state: {}, } as SocketService; (reconnectSocket as jest.Mock).mockResolvedValue(true); @@ -35,7 +35,7 @@ describe('checkFocusAndReconnect', () => { }); it('should immediately attempt reconnection if document has focus', () => { - mockHasFocus.mockReturnValueOnce(true); + mockHasFocus.mockReturnValue(true); checkFocusAndReconnect(instance); diff --git a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/connectToChannel.test.ts b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/connectToChannel.test.ts index 835de89a7..9e8a1b66b 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/connectToChannel.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/connectToChannel.test.ts @@ -2,6 +2,7 @@ import { setupChannelListeners } from '../ChannelManager'; import { EventType } from '../../../types/EventType'; import { SocketService } from '../../../SocketService'; +import * as loggerModule from '../../../utils/logger'; import { connectToChannel } from './connectToChannel'; jest.mock('../ChannelManager'); @@ -12,6 +13,8 @@ const mockEmit = jest.fn(); describe('connectToChannel', () => { let instance: SocketService; + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); + beforeEach(() => { jest.clearAllMocks(); @@ -66,10 +69,7 @@ describe('connectToChannel', () => { }).toThrow('socket already connected'); }); - it('should log debug information when debugging is enabled', () => { - instance.state.debug = true; - - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); + it('should log debug information', () => { const options = { channelId: 'channel123', withKeyExchange: true, @@ -78,11 +78,9 @@ describe('connectToChannel', () => { connectToChannel({ options, instance }); - expect(consoleDebugSpy).toHaveBeenCalledWith( - 'SocketService::someContext::connectToChannel() channelId=channel123 isOriginator=true', + expect(spyLogger).toHaveBeenCalledWith( + '[SocketService: connectToChannel()] context=someContext channelId=channel123 isOriginator=true', 'keyExchangeString', ); - - consoleDebugSpy.mockRestore(); }); }); diff --git a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/disconnect.test.ts b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/disconnect.test.ts index ea71d6ba5..76e14bbd4 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/disconnect.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/disconnect.test.ts @@ -1,8 +1,11 @@ import { SocketService } from '../../../SocketService'; +import * as loggerModule from '../../../utils/logger'; import { disconnect } from './disconnect'; describe('disconnect', () => { let instance: SocketService; + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); const mockDisconnect = jest.fn(); const mockClean = jest.fn(); @@ -29,18 +32,13 @@ describe('disconnect', () => { expect(mockDisconnect).toHaveBeenCalled(); }); - it('should log debug information when debugging is enabled', () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - + it('should log debug information', () => { disconnect(instance); - expect(consoleDebugSpy).toHaveBeenCalledWith( - 'SocketService::someContext::disconnect()', + expect(spyLogger).toHaveBeenCalledWith( + '[SocketService: disconnect()] context=someContext', undefined, ); - - consoleDebugSpy.mockRestore(); }); it('should handle termination and key exchange clean when provided', () => { diff --git a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/pause.test.ts b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/pause.test.ts index c6b22c3fd..e688ed0a8 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/pause.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/pause.test.ts @@ -1,9 +1,12 @@ import { SocketService } from '../../../SocketService'; import { MessageType } from '../../../types/MessageType'; +import * as loggerModule from '../../../utils/logger'; import { pause } from './pause'; describe('pause', () => { let instance: SocketService; + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); const mockDisconnect = jest.fn(); const mockAreKeysExchanged = jest.fn(); const mockSendMessage = jest.fn(); @@ -32,17 +35,12 @@ describe('pause', () => { expect(mockDisconnect).toHaveBeenCalled(); }); - it('should log debug information when debugging is enabled', () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - + it('should log debug information', () => { pause(instance); - expect(consoleDebugSpy).toHaveBeenCalledWith( - 'SocketService::someContext::pause()', + expect(spyLogger).toHaveBeenCalledWith( + '[SocketService: pause()] context=someContext', ); - - consoleDebugSpy.mockRestore(); }); it('should set manualDisconnect to true', () => { diff --git a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/ping.test.ts b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/ping.test.ts index c8478c7d6..f2efe5716 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/ping.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/ping.test.ts @@ -1,8 +1,10 @@ import { SocketService } from '../../../SocketService'; +import * as loggerModule from '../../../utils/logger'; import { ping } from './ping'; describe('ping', () => { let instance: SocketService; + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); const mockEmit = jest.fn(); const mockSendMessage = jest.fn(); const mockAreKeysExchanged = jest.fn(); @@ -29,16 +31,11 @@ describe('ping', () => { } as unknown as SocketService; }); - it('should log debug information when debugging is enabled', () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - + it('should log debug information', () => { ping(instance); - expect(consoleDebugSpy).toHaveBeenCalledWith( - expect.stringContaining('SocketService::someContext::ping()'), + expect(spyLogger).toHaveBeenCalledWith( + '[SocketService: ping()] context=someContext originator=false keysExchanged=undefined', ); - - consoleDebugSpy.mockRestore(); }); }); diff --git a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/reconnectSocket.test.ts b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/reconnectSocket.test.ts index 13f5c1628..c739686ed 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/reconnectSocket.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/reconnectSocket.test.ts @@ -2,6 +2,7 @@ import { SocketService } from '../../../SocketService'; import { EventType } from '../../../types/EventType'; import { wait } from '../../../utils/wait'; +import * as loggerModule from '../../../utils/logger'; import { reconnectSocket } from './reconnectSocket'; jest.mock('../../../utils/wait', () => ({ @@ -14,6 +15,8 @@ describe('reconnectSocket', () => { const mockEmitInstance = jest.fn(); const mockEmitSocket = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); + beforeEach(() => { jest.clearAllMocks(); @@ -34,18 +37,13 @@ describe('reconnectSocket', () => { (wait as jest.Mock).mockResolvedValue(undefined); }); - it('should log debug information when debugging is enabled', async () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - + it('should log debug information', async () => { await reconnectSocket(instance); - expect(consoleDebugSpy).toHaveBeenCalledWith( - expect.stringContaining('SocketService::connectAgain'), + expect(spyLogger).toHaveBeenCalledWith( + '[SocketService: reconnectSocket()] instance.state.socket?.connected=false trying to reconnect after socketio disconnection', instance, ); - - consoleDebugSpy.mockRestore(); }); it('should wait for a brief delay', async () => { diff --git a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/resume.test.ts b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/resume.test.ts index fe4b9b793..ef6d25992 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/resume.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/ConnectionManager/resume.test.ts @@ -2,10 +2,13 @@ import { SocketService } from '../../../SocketService'; import { EventType } from '../../../types/EventType'; import { MessageType } from '../../../types/MessageType'; +import * as loggerModule from '../../../utils/logger'; import { resume } from './resume'; describe('resume', () => { let instance: SocketService; + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); const mockConnect = jest.fn(); const mockEmit = jest.fn(); const mockSendMessage = jest.fn(); @@ -17,7 +20,6 @@ describe('resume', () => { instance = { state: { - debug: false, context: 'someContext', isOriginator: false, channelId: 'sampleChannelId', @@ -35,17 +37,16 @@ describe('resume', () => { } as unknown as SocketService; }); - it('should log debug information when debugging is enabled', () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - + it('should log debug information', () => { resume(instance); - expect(consoleDebugSpy).toHaveBeenCalledWith( - expect.stringContaining('SocketService::someContext::resume()'), + expect(spyLogger).toHaveBeenCalledWith( + '[SocketService: resume()] context=someContext connected=false manualDisconnect=undefined resumed=undefined keysExchanged=undefined', ); - consoleDebugSpy.mockRestore(); + expect(spyLogger).toHaveBeenCalledWith( + '[SocketService: resume()] after connecting socket --> connected=false', + ); }); it('should not connect socket if already connected', () => { @@ -68,7 +69,7 @@ describe('resume', () => { }); it('should send READY message if keys have been exchanged and not an originator', () => { - mockAreKeysExchanged.mockReturnValueOnce(true); + mockAreKeysExchanged.mockReturnValue(true); resume(instance); @@ -78,7 +79,7 @@ describe('resume', () => { it('should not send READY message if an originator, but initiate key exchange', () => { instance.state.isOriginator = true; - mockAreKeysExchanged.mockReturnValueOnce(true); + mockAreKeysExchanged.mockReturnValue(true); resume(instance); @@ -86,7 +87,7 @@ describe('resume', () => { }); it('should start key exchange if keys are not exchanged and not an originator', () => { - mockAreKeysExchanged.mockReturnValueOnce(false); + mockAreKeysExchanged.mockReturnValue(false); resume(instance); diff --git a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleChannelCreated.test.ts b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleChannelCreated.test.ts index 7eb6eccff..3f9da6eee 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleChannelCreated.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleChannelCreated.test.ts @@ -1,10 +1,14 @@ import { SocketService } from '../../../SocketService'; import { EventType } from '../../../types/EventType'; +import * as loggerModule from '../../../utils/logger'; import { handleChannelCreated } from './handleChannelCreated'; describe('handleChannelCreated', () => { let instance: SocketService; + const channelId = 'sampleChannelId'; + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); const mockEmit = jest.fn(); beforeEach(() => { @@ -24,19 +28,14 @@ describe('handleChannelCreated', () => { expect(typeof handler).toBe('function'); }); - it('should log debug information when debugging is enabled and the handler is called', () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - + it('should log debug information', () => { const handler = handleChannelCreated(instance, channelId); handler('someId'); - expect(consoleDebugSpy).toHaveBeenCalledWith( - `SocketService::${instance.state.context}::setupChannelListener::on 'channel_created-${channelId}'`, + expect(spyLogger).toHaveBeenCalledWith( + "[SocketService: handleChannelCreated()] context=someContext on 'channel_created-sampleChannelId'", 'someId', ); - - consoleDebugSpy.mockRestore(); }); it('should emit CHANNEL_CREATED event with the passed ID when the handler is called', () => { diff --git a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleClientsConnected.test.ts b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleClientsConnected.test.ts index 926f638c7..ef1f6d143 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleClientsConnected.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleClientsConnected.test.ts @@ -1,9 +1,12 @@ import { SocketService } from '../../../SocketService'; import { EventType } from '../../../types/EventType'; +import * as loggerModule from '../../../utils/logger'; import { handleClientsConnected } from './handleClientsConnected'; describe('handleClientsConnected', () => { let instance: SocketService; + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); const channelId = 'sampleChannelId'; const mockEmit = jest.fn(); const mockStart = jest.fn(); @@ -29,20 +32,17 @@ describe('handleClientsConnected', () => { } as unknown as SocketService; }); - it('should log debug information when debugging is enabled and the handler is called', async () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - + it('should log debug information', async () => { const handler = handleClientsConnected(instance, channelId); await handler('someId'); - expect(consoleDebugSpy).toHaveBeenCalledWith( - expect.stringContaining( - `SocketService::${instance.state.context}::setupChannelListener::on 'clients_connected-${channelId}'`, - ), + expect(spyLogger).toHaveBeenCalledWith( + "[SocketService: handleClientsConnected()] context=someContext on 'clients_connected-sampleChannelId' resumed=false clientsPaused=false keysExchanged=undefined isOriginator=false", ); - consoleDebugSpy.mockRestore(); + expect(spyLogger).toHaveBeenCalledWith( + "[SocketService: handleClientsConnected()] context=someContext on 'clients_connected' / keysExchanged=undefined -- backward compatibility", + ); }); it('should emit CLIENTS_CONNECTED event with the proper data when the handler is called', async () => { diff --git a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleClientsWaitingToJoin.test.ts b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleClientsWaitingToJoin.test.ts index b0331a97d..267f75ae0 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleClientsWaitingToJoin.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleClientsWaitingToJoin.test.ts @@ -1,9 +1,12 @@ import { SocketService } from '../../../SocketService'; import { EventType } from '../../../types/EventType'; +import * as loggerModule from '../../../utils/logger'; import { handleClientsWaitingToJoin } from './handleClientsWaitingToJoin'; describe('handleClientsWaitingToJoin', () => { let instance: SocketService; + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); const channelId = 'sampleChannelId'; const mockEmit = jest.fn(); @@ -20,20 +23,13 @@ describe('handleClientsWaitingToJoin', () => { }); it('should log debug information when debugging is enabled and the handler is called', () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - const handler = handleClientsWaitingToJoin(instance, channelId); handler(5); - expect(consoleDebugSpy).toHaveBeenCalledWith( - expect.stringContaining( - `SocketService::${instance.state.context}::setupChannelListener::on 'clients_waiting_to_join-${channelId}'`, - ), + expect(spyLogger).toHaveBeenCalledWith( + `[SocketService: handleClientsWaitingToJoin()] context=${instance.state.context} on 'clients_waiting_to_join-${channelId}'`, 5, ); - - consoleDebugSpy.mockRestore(); }); it('should emit CLIENTS_WAITING event with the number of waiting users', () => { diff --git a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleDisconnect.test.ts b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleDisconnect.test.ts index 8f1b584bf..460d688d9 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleDisconnect.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleDisconnect.test.ts @@ -1,12 +1,15 @@ import { SocketService } from '../../../SocketService'; import { EventType } from '../../../types/EventType'; import * as ConnectionManager from '../ConnectionManager'; +import * as loggerModule from '../../../utils/logger'; import { handleDisconnect } from './handleDisconnect'; jest.mock('../ConnectionManager'); describe('handleDisconnect', () => { let instance: SocketService; + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); const mockEmit = jest.fn(); const checkFocusAndReconnect = ConnectionManager.checkFocusAndReconnect as jest.Mock; @@ -24,20 +27,13 @@ describe('handleDisconnect', () => { }); it('should log debug information when debugging is enabled and the handler is called', () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - const handler = handleDisconnect(instance); handler('someReason'); - expect(consoleDebugSpy).toHaveBeenCalledWith( - expect.stringContaining( - `SocketService::on 'disconnect' manualDisconnect=${instance.state.manualDisconnect}`, - ), + expect(spyLogger).toHaveBeenCalledWith( + "[SocketService: handleDisconnect()] on 'disconnect' manualDisconnect=false", 'someReason', ); - - consoleDebugSpy.mockRestore(); }); it('should emit SOCKET_DISCONNECTED event and attempt to reconnect when disconnection was not manual', () => { diff --git a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleKeyInfo.test.ts b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleKeyInfo.test.ts index 4eb852e29..d50256ce2 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleKeyInfo.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleKeyInfo.test.ts @@ -1,35 +1,31 @@ import { SocketService } from '../../../SocketService'; import { EventType } from '../../../types/EventType'; +import * as loggerModule from '../../../utils/logger'; import { handleKeyInfo } from './handleKeyInfo'; describe('handleKeyInfo', () => { let instance: SocketService; + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); const mockEmit = jest.fn(); beforeEach(() => { jest.clearAllMocks(); instance = { - state: { - debug: false, - }, emit: mockEmit, } as unknown as SocketService; }); it('should log debug information when debugging is enabled and the handler is called', () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - const handler = handleKeyInfo(instance); const mockEventData = { someKey: 'someValue' }; handler(mockEventData); - expect(consoleDebugSpy).toHaveBeenCalledWith( - `SocketService::on 'KEY_INFO'`, + expect(spyLogger).toHaveBeenCalledWith( + "[SocketService: handleKeyInfo()] on 'KEY_INFO'", mockEventData, ); - consoleDebugSpy.mockRestore(); }); it('should emit KEY_INFO event with the provided event data', () => { diff --git a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleKeysExchanged.test.ts b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleKeysExchanged.test.ts index cdc0e5fd4..2546b7cec 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleKeysExchanged.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleKeysExchanged.test.ts @@ -1,9 +1,12 @@ import { SocketService } from '../../../SocketService'; import { EventType } from '../../../types/EventType'; +import * as loggerModule from '../../../utils/logger'; import { handleKeysExchanged } from './handleKeysExchanged'; describe('handleKeysExchanged', () => { let instance: SocketService; + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); const mockEmit = jest.fn(); const mockGetKeyInfo = jest.fn(); @@ -12,7 +15,6 @@ describe('handleKeysExchanged', () => { instance = { state: { - debug: false, isOriginator: false, keyExchange: { areKeysExchanged: jest.fn().mockReturnValue(true), @@ -24,16 +26,12 @@ describe('handleKeysExchanged', () => { }); it('should log debug information when debugging is enabled and the handler is called', () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - const handler = handleKeysExchanged(instance); handler(); - expect(consoleDebugSpy).toHaveBeenCalledWith( - `SocketService::on 'keys_exchanged' keyschanged=true`, + expect(spyLogger).toHaveBeenCalledWith( + "[SocketService: handleKeysExchanged()] on 'keys_exchanged' keyschanged=true", ); - consoleDebugSpy.mockRestore(); }); it('should emit KEYS_EXCHANGED event with the keys exchanged status and isOriginator', () => { diff --git a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleMessage.test.ts b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleMessage.test.ts index 45c9327c1..6dd9b9419 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleMessage.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleMessage.test.ts @@ -4,6 +4,7 @@ import { InternalEventType } from '../../../types/InternalEventType'; import { KeyExchangeMessageType } from '../../../types/KeyExchangeMessageType'; import { MessageType } from '../../../types/MessageType'; import * as ChannelManager from '../ChannelManager'; +import * as loggerModule from '../../../utils/logger'; import { handleMessage } from './handleMessage'; jest.mock('../ChannelManager'); @@ -13,6 +14,8 @@ const msgToDeEncrypt = 'encryptedMessage'; describe('handleMessage', () => { let instance: SocketService; + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); + const mockCheckSameId = ChannelManager.checkSameId as jest.Mock; const mockEmit = jest.fn(); const mockAreKeysExchanged = jest.fn(); @@ -49,21 +52,18 @@ describe('handleMessage', () => { } as unknown as SocketService; }); - it('should log debug information when debugging is enabled and the handler is called', () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - + it('should log debug information', () => { const handler = handleMessage(instance, channelId); handler({ id: 'testId', message: { type: MessageType.PING } }); - expect(consoleDebugSpy).toHaveBeenCalledWith( - `SocketService::${ - instance.state.context - }::on 'message' ${channelId} keysExchanged=${instance.state.keyExchange?.areKeysExchanged()}`, - { type: MessageType.PING }, + expect(spyLogger).toHaveBeenCalledWith( + "[SocketService handleMessage()] context=undefined on 'message' testChannel keysExchanged=undefined", + { type: 'ping' }, ); - consoleDebugSpy.mockRestore(); + expect(spyLogger).toHaveBeenCalledWith( + "[SocketService handleMessage()] context=undefined::on 'message' ping ", + ); }); it('should emit MESSAGE event with ping type when a PING message is received', () => { @@ -87,7 +87,7 @@ describe('handleMessage', () => { it('should emit the decrypted MESSAGE when keys are exchanged', () => { mockAreKeysExchanged.mockReturnValueOnce(true); - mockDecryptMessage.mockReturnValueOnce( + mockDecryptMessage.mockReturnValue( JSON.stringify({ type: MessageType.PAUSE }), ); @@ -158,7 +158,7 @@ describe('handleMessage', () => { it('should emit non-encrypted unknown message', () => { mockAreKeysExchanged.mockReturnValueOnce(true); - mockDecryptMessage.mockReturnValueOnce( + mockDecryptMessage.mockReturnValue( JSON.stringify({ type: 'testType', data: 'testData', @@ -184,7 +184,7 @@ describe('handleMessage', () => { it('should set clientsPaused to true if a decrypted PAUSE message is received', () => { mockAreKeysExchanged.mockReturnValueOnce(true); - mockDecryptMessage.mockReturnValueOnce( + mockDecryptMessage.mockReturnValue( JSON.stringify({ type: MessageType.PAUSE }), ); @@ -215,7 +215,7 @@ describe('handleMessage', () => { it('should emit a decrypted message after successful decryption', () => { mockAreKeysExchanged.mockReturnValueOnce(true); - mockDecryptMessage.mockReturnValueOnce( + mockDecryptMessage.mockReturnValue( JSON.stringify({ type: 'testType', data: 'testData' }), ); @@ -226,15 +226,4 @@ describe('handleMessage', () => { message: { type: 'testType', data: 'testData' }, }); }); - - it('should start key exchange if an encrypted message is received before keys are exchanged and is an originator', () => { - mockAreKeysExchanged.mockReturnValueOnce(false); - instance.state.isOriginator = true; - - const handler = handleMessage(instance, channelId); - handler({ id: 'testId', message: msgToDeEncrypt }); - - // TODO proper error handling - expect(true).toBe(true); - }); }); diff --git a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handlePing.test.ts b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handlePing.test.ts index c4e976821..940fa8763 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handlePing.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handlePing.test.ts @@ -1,37 +1,19 @@ -import { SocketService } from '../../../SocketService'; +import * as loggerModule from '../../../utils/logger'; import { handlePing } from './handlePing'; describe('handlePing', () => { - let instance: SocketService; - const mockConsoleDebug = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); beforeEach(() => { jest.clearAllMocks(); - - instance = { - state: { - debug: false, - }, - } as unknown as SocketService; - - jest.spyOn(console, 'debug').mockImplementation(mockConsoleDebug); - }); - - it('should log a debug message when the handler is called and debugging is enabled', () => { - instance.state.debug = true; - - const handler = handlePing(instance); - handler(); - - expect(mockConsoleDebug).toHaveBeenCalledWith(`SocketService::on 'ping'`); }); - it('should not log a debug message when debugging is disabled', () => { - instance.state.debug = false; - - const handler = handlePing(instance); + it('should log a debug message when the handler is called', () => { + const handler = handlePing(); handler(); - expect(mockConsoleDebug).not.toHaveBeenCalled(); + expect(spyLogger).toHaveBeenCalledWith( + "[SocketService: handlePing()] on 'ping'", + ); }); }); diff --git a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleReconnect.test.ts b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleReconnect.test.ts index 8a8fb8de0..34815bbe9 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleReconnect.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleReconnect.test.ts @@ -1,39 +1,19 @@ -import { SocketService } from '../../../SocketService'; +import * as loggerModule from '../../../utils/logger'; import { handleReconnect } from './handleReconnect'; describe('handleReconnect', () => { - let instance: SocketService; - const mockConsoleDebug = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); beforeEach(() => { jest.clearAllMocks(); - - instance = { - state: { - debug: false, - }, - } as unknown as SocketService; - - jest.spyOn(console, 'debug').mockImplementation(mockConsoleDebug); }); - it('should log a debug message with attempt number when the handler is called and debugging is enabled', () => { - instance.state.debug = true; - - const handler = handleReconnect(instance); + it('should log a debug message with attempt number when the handler is called', () => { + const handler = handleReconnect(); handler(5); - expect(mockConsoleDebug).toHaveBeenCalledWith( - `SocketService::on 'reconnect' attempt=5`, + expect(spyLogger).toHaveBeenCalledWith( + "[SocketService: handleReconnect()] on 'reconnect' attempt=5", ); }); - - it('should not log a debug message when debugging is disabled', () => { - instance.state.debug = false; - - const handler = handleReconnect(instance); - handler(3); - - expect(mockConsoleDebug).not.toHaveBeenCalled(); - }); }); diff --git a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleReconnectError.test.ts b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleReconnectError.test.ts index d84787b56..884018538 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleReconnectError.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleReconnectError.test.ts @@ -1,42 +1,22 @@ -import { SocketService } from '../../../SocketService'; +import * as loggerModule from '../../../utils/logger'; import { handleReconnectError } from './handleReconnectError'; describe('handleReconnectError', () => { - let instance: SocketService; - const mockConsoleDebug = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); beforeEach(() => { jest.clearAllMocks(); - - instance = { - state: { - debug: false, - }, - } as unknown as SocketService; - - jest.spyOn(console, 'debug').mockImplementation(mockConsoleDebug); }); it('should log a debug message with error details when the handler is called and debugging is enabled', () => { - instance.state.debug = true; const mockError = new Error('Reconnect error'); - const handler = handleReconnectError(instance); + const handler = handleReconnectError(); handler(mockError); - expect(mockConsoleDebug).toHaveBeenCalledWith( - `SocketService::on 'reconnect_error'`, + expect(spyLogger).toHaveBeenCalledWith( + "[SocketService: handleReconnectError()] on 'reconnect_error'", mockError, ); }); - - it('should not log a debug message when debugging is disabled', () => { - instance.state.debug = false; - const mockError = new Error('Reconnect error'); - - const handler = handleReconnectError(instance); - handler(mockError); - - expect(mockConsoleDebug).not.toHaveBeenCalled(); - }); }); diff --git a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleReconnectFailed.test.ts b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleReconnectFailed.test.ts index 5ffad1143..1a14a1e30 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleReconnectFailed.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleReconnectFailed.test.ts @@ -1,9 +1,10 @@ import { SocketService } from '../../../SocketService'; +import * as loggerModule from '../../../utils/logger'; import { handleReconnectFailed } from './handleReconnectFailed'; describe('handleReconnectFailed', () => { let instance: SocketService; - const mockConsoleDebug = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); beforeEach(() => { jest.clearAllMocks(); @@ -13,27 +14,16 @@ describe('handleReconnectFailed', () => { debug: false, }, } as unknown as SocketService; - - jest.spyOn(console, 'debug').mockImplementation(mockConsoleDebug); }); it('should log a debug message indicating that reconnection attempts have failed when the handler is called and debugging is enabled', () => { instance.state.debug = true; - const handler = handleReconnectFailed(instance); + const handler = handleReconnectFailed(); handler(); - expect(mockConsoleDebug).toHaveBeenCalledWith( - `SocketService::on 'reconnect_failed'`, + expect(spyLogger).toHaveBeenCalledWith( + "[SocketService: handleReconnectFailed()] on 'reconnect_failed'", ); }); - - it('should not log a debug message when debugging is disabled', () => { - instance.state.debug = false; - - const handler = handleReconnectFailed(instance); - handler(); - - expect(mockConsoleDebug).not.toHaveBeenCalled(); - }); }); diff --git a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleSocketError.test.ts b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleSocketError.test.ts index e7d72c50a..ec2a5f5c8 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleSocketError.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handleSocketError.test.ts @@ -1,12 +1,14 @@ import { SocketService } from '../../../SocketService'; import { checkFocusAndReconnect } from '../ConnectionManager'; +import * as loggerModule from '../../../utils/logger'; import { handleSocketError } from './handleSocketError'; jest.mock('../ConnectionManager'); describe('handleSocketError', () => { let instance: SocketService; - const mockConsoleDebug = jest.fn(); + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); const error = new Error('Test error'); beforeEach(() => { @@ -17,31 +19,18 @@ describe('handleSocketError', () => { debug: false, }, } as unknown as SocketService; - - jest.spyOn(console, 'debug').mockImplementation(mockConsoleDebug); }); it('should log the error when debugging is enabled', () => { - instance.state.debug = true; - const handler = handleSocketError(instance); handler(error); - expect(mockConsoleDebug).toHaveBeenCalledWith( - `SocketService::on 'error' `, + expect(spyLogger).toHaveBeenCalledWith( + `[SocketService: handleSocketError()] on 'error' `, error, ); }); - it('should not log the error when debugging is disabled', () => { - instance.state.debug = false; - - const handler = handleSocketError(instance); - handler(error); - - expect(mockConsoleDebug).not.toHaveBeenCalled(); - }); - it('should call the checkFocusAndReconnect function', () => { const handler = handleSocketError(instance); handler(error); diff --git a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handlesClientsDisconnected.test.ts b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handlesClientsDisconnected.test.ts index 51d40e2dd..9a4c00b1f 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handlesClientsDisconnected.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/EventListeners/handlesClientsDisconnected.test.ts @@ -1,9 +1,13 @@ import { SocketService } from '../../../SocketService'; import { EventType } from '../../../types/EventType'; +import * as loggerModule from '../../../utils/logger'; import { handlesClientsDisconnected } from './handlesClientsDisconnected'; describe('handlesClientsDisconnected', () => { let instance: SocketService; + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); + const mockConsoleDebug = jest.fn(); const mockEmit = jest.fn(); const channelId = 'testChannel'; @@ -36,14 +40,12 @@ describe('handlesClientsDisconnected', () => { expect(instance.state.clientsConnected).toBe(false); }); - it('should log a debug message when debugging is enabled', () => { - instance.state.debug = true; - + it('should log a debug info', () => { const handler = handlesClientsDisconnected(instance, channelId); handler(); - expect(mockConsoleDebug).toHaveBeenCalledWith( - `SocketService::testContext::setupChannelListener::on 'clients_disconnected-${channelId}'`, + expect(spyLogger).toHaveBeenCalledWith( + "[SocketService: handlesClientsDisconnected()] context=testContext on 'clients_disconnected-testChannel'", ); }); diff --git a/packages/sdk-communication-layer/src/services/SocketService/KeysManager/handleKeyHandshake.test.ts b/packages/sdk-communication-layer/src/services/SocketService/KeysManager/handleKeyHandshake.test.ts index bada2936e..0700e3b86 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/KeysManager/handleKeyHandshake.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/KeysManager/handleKeyHandshake.test.ts @@ -2,11 +2,13 @@ import { SocketService } from '../../../SocketService'; import { CommunicationLayerMessage } from '../../../types/CommunicationLayerMessage'; import { EventType } from '../../../types/EventType'; import { KeyExchangeMessageType } from '../../../types/KeyExchangeMessageType'; +import * as loggerModule from '../../../utils/logger'; import { handleKeyHandshake } from './handleKeyHandshake'; describe('handleKeyHandshake', () => { let instance: SocketService; - const mockConsoleDebug = jest.fn(); + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); const mockEmit = jest.fn(); const keyHandshakeMessage: CommunicationLayerMessage = { @@ -27,17 +29,13 @@ describe('handleKeyHandshake', () => { }, }, } as unknown as SocketService; - - jest.spyOn(console, 'debug').mockImplementation(mockConsoleDebug); }); - it('should log the message when debugging is enabled', () => { - instance.state.debug = true; - + it('should log the message', () => { handleKeyHandshake(instance, keyHandshakeMessage); - expect(mockConsoleDebug).toHaveBeenCalledWith( - `SocketService::${instance.state.context}::sendMessage()`, + expect(spyLogger).toHaveBeenCalledWith( + '[SocketService: handleKeyHandshake()] context=testContext', keyHandshakeMessage, ); }); diff --git a/packages/sdk-communication-layer/src/services/SocketService/KeysManager/resetKeys.test.ts b/packages/sdk-communication-layer/src/services/SocketService/KeysManager/resetKeys.test.ts index e2748ed00..accb1422c 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/KeysManager/resetKeys.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/KeysManager/resetKeys.test.ts @@ -1,4 +1,5 @@ import { SocketService } from '../../../SocketService'; +import * as loggerModule from '../../../utils/logger'; import { resetKeys } from './resetKeys'; describe('resetKeys', () => { @@ -6,6 +7,8 @@ describe('resetKeys', () => { const mockConsoleDebug = jest.spyOn(console, 'debug'); const mockResetKeys = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); + beforeEach(() => { jest.clearAllMocks(); @@ -24,14 +27,11 @@ describe('resetKeys', () => { expect(mockResetKeys).toHaveBeenCalled(); }); - it('should not log debug message if debugging is disabled', () => { - resetKeys(instance); - expect(mockConsoleDebug).not.toHaveBeenCalled(); - }); - - it('should log debug message if debugging is enabled', () => { + it('should log debug message', () => { instance.state.debug = true; resetKeys(instance); - expect(mockConsoleDebug).toHaveBeenCalledWith('SocketService::resetKeys()'); + expect(spyLogger).toHaveBeenCalledWith( + '[SocketService: resetKeys()] Resetting keys.', + ); }); }); diff --git a/packages/sdk-communication-layer/src/services/SocketService/KeysManager/validateKeyExchange.test.ts b/packages/sdk-communication-layer/src/services/SocketService/KeysManager/validateKeyExchange.test.ts index b4739979e..52d7491a0 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/KeysManager/validateKeyExchange.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/KeysManager/validateKeyExchange.test.ts @@ -1,11 +1,14 @@ import { SocketService } from '../../../SocketService'; import { CommunicationLayerMessage } from '../../../types/CommunicationLayerMessage'; import { KeyExchangeMessageType } from '../../../types/KeyExchangeMessageType'; +import * as loggerModule from '../../../utils/logger'; import { validateKeyExchange } from './validateKeyExchange'; describe('validateKeyExchange', () => { let instance: SocketService; - const mockConsoleDebug = jest.spyOn(console, 'debug'); + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); + const mockAreKeysExchanged = jest.fn(); const testMessage: CommunicationLayerMessage = { type: KeyExchangeMessageType.KEY_HANDSHAKE_START, @@ -17,7 +20,6 @@ describe('validateKeyExchange', () => { instance = { state: { - debug: false, context: 'testContext', keyExchange: { areKeysExchanged: mockAreKeysExchanged, @@ -48,8 +50,8 @@ describe('validateKeyExchange', () => { // do nothing } - expect(mockConsoleDebug).toHaveBeenCalledWith( - `SocketService::testContext::sendMessage() ERROR keys not exchanged`, + expect(spyLogger).toHaveBeenCalledWith( + '[SocketService: validateKeyExchange()] context=testContext ERROR keys not exchanged', testMessage, ); }); diff --git a/packages/sdk-communication-layer/src/services/SocketService/MessageHandlers/encryptAndSendMessage.test.ts b/packages/sdk-communication-layer/src/services/SocketService/MessageHandlers/encryptAndSendMessage.test.ts index 823e97c5c..c258ba703 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/MessageHandlers/encryptAndSendMessage.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/MessageHandlers/encryptAndSendMessage.test.ts @@ -1,13 +1,17 @@ import { SocketService } from '../../../SocketService'; import { CommunicationLayerMessage } from '../../../types/CommunicationLayerMessage'; import { MessageType } from '../../../types/MessageType'; +import * as loggerModule from '../../../utils/logger'; import { encryptAndSendMessage } from './encryptAndSendMessage'; describe('encryptAndSendMessage', () => { let instance: SocketService; + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); + const mockEncryptMessage = jest.fn(); const mockEmit = jest.fn(); - const mockConsoleDebug = jest.spyOn(console, 'debug'); + const testMessage: CommunicationLayerMessage = { type: MessageType.PAUSE, data: {}, @@ -61,10 +65,20 @@ describe('encryptAndSendMessage', () => { ); }); - it('should log debug message if debugging is enabled', () => { - instance.state.debug = true; + it('should log debug info', () => { + const messageToSend = { + id: instance.state.channelId, + context: instance.state.context, + message: 'encryptedMessage', + plaintext: undefined, + }; + encryptAndSendMessage(instance, testMessage); - expect(mockConsoleDebug).toHaveBeenCalled(); + + expect(spyLogger).toHaveBeenCalledWith( + '[SocketService: encryptAndSendMessage()] context=testContext', + messageToSend, + ); }); it('should set manualDisconnect if message type is TERMINATE', () => { diff --git a/packages/sdk-communication-layer/src/services/SocketService/MessageHandlers/handleRpcReplies.test.ts b/packages/sdk-communication-layer/src/services/SocketService/MessageHandlers/handleRpcReplies.test.ts index 715f8fd2b..9dfac4b5c 100644 --- a/packages/sdk-communication-layer/src/services/SocketService/MessageHandlers/handleRpcReplies.test.ts +++ b/packages/sdk-communication-layer/src/services/SocketService/MessageHandlers/handleRpcReplies.test.ts @@ -1,21 +1,23 @@ import { SocketService } from '../../../SocketService'; import { CommunicationLayerMessage } from '../../../types/CommunicationLayerMessage'; import { waitForRpc } from '../../../utils/wait'; +import * as loggerModule from '../../../utils/logger'; import { handleRpcReplies } from './handleRpcReplies'; jest.mock('../../../utils/wait'); describe('handleRpcReplies', () => { let instance: SocketService; + + const spyLogger = jest.spyOn(loggerModule, 'loggerServiceLayer'); + const mockWaitForRpc = waitForRpc as jest.MockedFunction; beforeEach(() => { jest.clearAllMocks(); instance = { - state: { - debug: true, - }, + state: {}, } as unknown as SocketService; mockWaitForRpc.mockResolvedValue({ @@ -65,9 +67,6 @@ describe('handleRpcReplies', () => { }; instance.state.isOriginator = true; - instance.state.debug = true; - - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); mockWaitForRpc.mockResolvedValueOnce({ id: '123', @@ -79,8 +78,8 @@ describe('handleRpcReplies', () => { await handleRpcReplies(instance, message); - expect(consoleDebugSpy).toHaveBeenCalledWith( - 'SocketService::waitForRpc id=123 testMethod ( 100 ms)', + expect(spyLogger).toHaveBeenCalledWith( + '[SocketService:handleRpcReplies()] id=123 testMethod ( 100 ms)', 'success', ); }); diff --git a/packages/sdk-react/src/EventsHandlers/useHandleChainChangedEvent.test.tsx b/packages/sdk-react/src/EventsHandlers/useHandleChainChangedEvent.test.tsx index 34517e73b..0e5069131 100644 --- a/packages/sdk-react/src/EventsHandlers/useHandleChainChangedEvent.test.tsx +++ b/packages/sdk-react/src/EventsHandlers/useHandleChainChangedEvent.test.tsx @@ -1,8 +1,11 @@ import { renderHook } from '@testing-library/react-hooks'; import { useHandleChainChangedEvent } from './useHandleChainChangedEvent'; import { EventHandlerProps } from '../MetaMaskProvider'; +import * as loggerModule from '../utils/logger'; describe('useHandleChainChangedEvent', () => { + const spyLogger = jest.spyOn(loggerModule, 'logger'); + const eventHandlerProps = { setConnected: jest.fn(), setError: jest.fn(), @@ -18,12 +21,9 @@ describe('useHandleChainChangedEvent', () => { eventHandlerProps.setConnected = jest.fn(); eventHandlerProps.setConnecting = jest.fn(); eventHandlerProps.setError = jest.fn(); - - console.debug = jest.fn(); }); - it('should handle chain changed event with object and debug enabled', () => { - eventHandlerProps.debug = true; + it('should handle chain changed event with object', () => { const mockNetworkVersion = { chainId: '0x1', networkVersion: '1', @@ -32,12 +32,14 @@ describe('useHandleChainChangedEvent', () => { const { result } = renderHook(() => useHandleChainChangedEvent(eventHandlerProps), ); + result.current(mockNetworkVersion); - expect(console.debug).toHaveBeenCalledWith( - "MetaMaskProvider::provider on 'chainChanged' event.", + expect(spyLogger).toHaveBeenCalledWith( + "[MetaMaskProvider: useHandleChainChangedEvent()] on 'chainChanged' event.", mockNetworkVersion, ); + expect(eventHandlerProps.setChainId).toHaveBeenCalledWith( mockNetworkVersion.chainId, ); @@ -46,8 +48,7 @@ describe('useHandleChainChangedEvent', () => { expect(eventHandlerProps.setError).toHaveBeenCalledWith(undefined); }); - it('should handle chain changed event with string and debug enabled', () => { - eventHandlerProps.debug = true; + it('should handle chain changed event with string', () => { const chainId = '0x1'; const { result } = renderHook(() => @@ -55,8 +56,8 @@ describe('useHandleChainChangedEvent', () => { ); result.current(chainId); - expect(console.debug).toHaveBeenCalledWith( - "MetaMaskProvider::provider on 'chainChanged' event.", + expect(spyLogger).toHaveBeenCalledWith( + "[MetaMaskProvider: useHandleChainChangedEvent()] on 'chainChanged' event.", chainId, ); expect(eventHandlerProps.setChainId).toHaveBeenCalledWith(chainId); @@ -64,20 +65,4 @@ describe('useHandleChainChangedEvent', () => { expect(eventHandlerProps.setConnecting).toHaveBeenCalledWith(false); expect(eventHandlerProps.setError).toHaveBeenCalledWith(undefined); }); - - it('should handle chain changed event without debug logs', () => { - eventHandlerProps.debug = false; - const chainId = '0x1'; - - const { result } = renderHook(() => - useHandleChainChangedEvent(eventHandlerProps), - ); - result.current(chainId); - - expect(console.debug).not.toHaveBeenCalled(); - expect(eventHandlerProps.setChainId).toHaveBeenCalledWith(chainId); - expect(eventHandlerProps.setConnected).toHaveBeenCalledWith(true); - expect(eventHandlerProps.setConnecting).toHaveBeenCalledWith(false); - expect(eventHandlerProps.setError).toHaveBeenCalledWith(undefined); - }); }); diff --git a/packages/sdk-react/src/EventsHandlers/useHandleConnectEvent.test.tsx b/packages/sdk-react/src/EventsHandlers/useHandleConnectEvent.test.tsx index ae3d31270..61c59e2b6 100644 --- a/packages/sdk-react/src/EventsHandlers/useHandleConnectEvent.test.tsx +++ b/packages/sdk-react/src/EventsHandlers/useHandleConnectEvent.test.tsx @@ -1,8 +1,11 @@ import { renderHook } from '@testing-library/react-hooks'; import { useHandleConnectEvent } from './useHandleConnectEvent'; import { EventHandlerProps } from '../MetaMaskProvider'; +import * as loggerModule from '../utils/logger'; describe('useHandleConnectEvent', () => { + const spyLogger = jest.spyOn(loggerModule, 'logger'); + const eventHandlerProps = { setConnected: jest.fn(), setError: jest.fn(), @@ -18,12 +21,9 @@ describe('useHandleConnectEvent', () => { eventHandlerProps.setConnected = jest.fn(); eventHandlerProps.setChainId = jest.fn(); eventHandlerProps.setError = jest.fn(); - - console.debug = jest.fn(); }); - it('should handle connect event correctly with debug enabled', () => { - eventHandlerProps.debug = true; + it('should handle connect event correctly ', () => { const mockConnectParam = { chainId: '0x2', }; @@ -33,8 +33,8 @@ describe('useHandleConnectEvent', () => { ); result.current(mockConnectParam); - expect(console.debug).toHaveBeenCalledWith( - "MetaMaskProvider::provider on 'connect' event.", + expect(spyLogger).toHaveBeenCalledWith( + "[MetaMaskProvider: useHandleConnectEvent()] on 'connect' event.", mockConnectParam, ); expect(eventHandlerProps.setConnecting).toHaveBeenCalledWith(false); @@ -45,28 +45,7 @@ describe('useHandleConnectEvent', () => { expect(eventHandlerProps.setError).toHaveBeenCalledWith(undefined); }); - it('should handle connect event without debug logs', () => { - eventHandlerProps.debug = false; - const mockConnectParam = { - chainId: '0x2', - }; - - const { result } = renderHook(() => - useHandleConnectEvent(eventHandlerProps), - ); - result.current(mockConnectParam); - - expect(console.debug).not.toHaveBeenCalled(); - expect(eventHandlerProps.setConnecting).toHaveBeenCalledWith(false); - expect(eventHandlerProps.setConnected).toHaveBeenCalledWith(true); - expect(eventHandlerProps.setChainId).toHaveBeenCalledWith( - mockConnectParam.chainId, - ); - expect(eventHandlerProps.setError).toHaveBeenCalledWith(undefined); - }); - it('should prioritize external chainId over connectParam chainId', () => { - eventHandlerProps.debug = false; const mockConnectParam = { chainId: '0x2', }; diff --git a/packages/sdk-react/src/EventsHandlers/useHandleDisconnectEvent.test.tsx b/packages/sdk-react/src/EventsHandlers/useHandleDisconnectEvent.test.tsx index 7045ce5ca..79efb3e4d 100644 --- a/packages/sdk-react/src/EventsHandlers/useHandleDisconnectEvent.test.tsx +++ b/packages/sdk-react/src/EventsHandlers/useHandleDisconnectEvent.test.tsx @@ -1,8 +1,11 @@ import { renderHook } from '@testing-library/react-hooks'; import { useHandleDisconnectEvent } from './useHandleDisconnectEvent'; import { EventHandlerProps } from '../MetaMaskProvider'; +import * as loggerModule from '../utils/logger'; describe('useHandleDisconnectEvent', () => { + const spyLogger = jest.spyOn(loggerModule, 'logger'); + const eventHandlerProps = { setConnected: jest.fn(), setError: jest.fn(), @@ -16,12 +19,9 @@ describe('useHandleDisconnectEvent', () => { eventHandlerProps.setConnecting = jest.fn(); eventHandlerProps.setConnected = jest.fn(); eventHandlerProps.setError = jest.fn(); - - console.debug = jest.fn(); }); - it('should handle disconnect event correctly with debug enabled', () => { - eventHandlerProps.debug = true; + it('should handle disconnect event correctly', () => { const mockReason = { message: 'Disconnected due to xyz', code: -32000 }; const { result } = renderHook(() => @@ -29,25 +29,11 @@ describe('useHandleDisconnectEvent', () => { ); result.current(mockReason); - expect(console.debug).toHaveBeenCalledWith( - "MetaMaskProvider::provider on 'disconnect' event.", + expect(spyLogger).toHaveBeenCalledWith( + "[MetaMaskProvider: useHandleDisconnectEvent()] on 'disconnect' event.", mockReason, ); - expect(eventHandlerProps.setConnecting).toHaveBeenCalledWith(false); - expect(eventHandlerProps.setConnected).toHaveBeenCalledWith(false); - expect(eventHandlerProps.setError).toHaveBeenCalledWith(mockReason); - }); - - it('should handle disconnect event without debug logs', () => { - eventHandlerProps.debug = false; - const mockReason = { message: 'Disconnected due to xyz', code: -32000 }; - - const { result } = renderHook(() => - useHandleDisconnectEvent(eventHandlerProps), - ); - result.current(mockReason); - expect(console.debug).not.toHaveBeenCalled(); expect(eventHandlerProps.setConnecting).toHaveBeenCalledWith(false); expect(eventHandlerProps.setConnected).toHaveBeenCalledWith(false); expect(eventHandlerProps.setError).toHaveBeenCalledWith(mockReason); diff --git a/packages/sdk-react/src/EventsHandlers/useHandleInitializedEvent.test.tsx b/packages/sdk-react/src/EventsHandlers/useHandleInitializedEvent.test.tsx index be744b665..55e852177 100644 --- a/packages/sdk-react/src/EventsHandlers/useHandleInitializedEvent.test.tsx +++ b/packages/sdk-react/src/EventsHandlers/useHandleInitializedEvent.test.tsx @@ -2,8 +2,11 @@ import { renderHook } from '@testing-library/react-hooks'; import { useHandleInitializedEvent } from './useHandleInitializedEvent'; import { EventHandlerProps } from '../MetaMaskProvider'; import { SDKProvider } from '@metamask/sdk'; +import * as loggerModule from '../utils/logger'; describe('useHandleInitializedEvent', () => { + const spyLogger = jest.spyOn(loggerModule, 'logger'); + const eventHandlerProps = { setConnected: jest.fn(), setError: jest.fn(), @@ -22,12 +25,9 @@ describe('useHandleInitializedEvent', () => { eventHandlerProps.setConnecting = jest.fn(); eventHandlerProps.debug = true; eventHandlerProps.activeProvider = {} as SDKProvider; - - console.debug = jest.fn(); }); it('should handle initialized event correctly with debug enabled', () => { - eventHandlerProps.debug = true; eventHandlerProps.activeProvider = { selectedAddress: '0x12345Abcdef', } as unknown as SDKProvider; @@ -37,26 +37,10 @@ describe('useHandleInitializedEvent', () => { ); result.current(); - expect(console.debug).toHaveBeenCalledWith( - "MetaMaskProvider::provider on '_initialized' event.", + expect(spyLogger).toHaveBeenCalledWith( + "[MetaMaskProvider: useHandleInitializedEvent()] on '_initialized' event.", ); - expect(eventHandlerProps.setConnecting).toHaveBeenCalledWith(false); - expect(eventHandlerProps.setConnected).toHaveBeenCalledWith(true); - expect(eventHandlerProps.setError).toHaveBeenCalledWith(undefined); - }); - - it('should handle initialized event without debug logs', () => { - eventHandlerProps.debug = false; - eventHandlerProps.activeProvider = { - selectedAddress: '0x12345Abcdef', - } as unknown as SDKProvider; - - const { result } = renderHook(() => - useHandleInitializedEvent(eventHandlerProps), - ); - result.current(); - expect(console.debug).not.toHaveBeenCalled(); expect(eventHandlerProps.setConnecting).toHaveBeenCalledWith(false); expect(eventHandlerProps.setConnected).toHaveBeenCalledWith(true); expect(eventHandlerProps.setError).toHaveBeenCalledWith(undefined); diff --git a/packages/sdk-react/src/EventsHandlers/useHandleOnConnectingEvent.test.tsx b/packages/sdk-react/src/EventsHandlers/useHandleOnConnectingEvent.test.tsx index 9d28f12aa..608bb9098 100644 --- a/packages/sdk-react/src/EventsHandlers/useHandleOnConnectingEvent.test.tsx +++ b/packages/sdk-react/src/EventsHandlers/useHandleOnConnectingEvent.test.tsx @@ -1,8 +1,11 @@ import { renderHook } from '@testing-library/react-hooks'; import { useHandleOnConnectingEvent } from './useHandleOnConnectingEvent'; import { EventHandlerProps } from '../MetaMaskProvider'; +import * as loggerModule from '../utils/logger'; describe('useHandleOnConnectingEvent', () => { + const spyLogger = jest.spyOn(loggerModule, 'logger'); + const eventHandlerProps = { setConnected: jest.fn(), setError: jest.fn(), @@ -16,35 +19,17 @@ describe('useHandleOnConnectingEvent', () => { eventHandlerProps.setConnected = jest.fn(); eventHandlerProps.setConnecting = jest.fn(); eventHandlerProps.setError = jest.fn(); - - console.debug = jest.fn(); }); - it('should handle connecting event correctly with debug enabled', () => { - eventHandlerProps.debug = true; - + it('should handle connecting event correctly', () => { const { result } = renderHook(() => useHandleOnConnectingEvent(eventHandlerProps), ); result.current(); - expect(console.debug).toHaveBeenCalledWith( - "MetaMaskProvider::provider on 'connecting' event.", - ); - expect(eventHandlerProps.setConnected).toHaveBeenCalledWith(false); - expect(eventHandlerProps.setConnecting).toHaveBeenCalledWith(true); - expect(eventHandlerProps.setError).toHaveBeenCalledWith(undefined); - }); - - it('should handle connecting event without debug logs', () => { - eventHandlerProps.debug = false; - - const { result } = renderHook(() => - useHandleOnConnectingEvent(eventHandlerProps), + expect(spyLogger).toHaveBeenCalledWith( + "[MetaMaskProvider: useHandleOnConnectingEvent()] on 'connecting' event.", ); - result.current(); - - expect(console.debug).not.toHaveBeenCalled(); expect(eventHandlerProps.setConnected).toHaveBeenCalledWith(false); expect(eventHandlerProps.setConnecting).toHaveBeenCalledWith(true); expect(eventHandlerProps.setError).toHaveBeenCalledWith(undefined); diff --git a/packages/sdk-react/src/EventsHandlers/useHandleProviderEvent.test.tsx b/packages/sdk-react/src/EventsHandlers/useHandleProviderEvent.test.tsx index f04bfcaaf..ec0f773e3 100644 --- a/packages/sdk-react/src/EventsHandlers/useHandleProviderEvent.test.tsx +++ b/packages/sdk-react/src/EventsHandlers/useHandleProviderEvent.test.tsx @@ -2,6 +2,7 @@ import { EventType, PROVIDER_UPDATE_TYPE } from '@metamask/sdk'; import { useHandleProviderEvent } from './useHandleProviderEvent'; import { renderHook } from '@testing-library/react-hooks'; import { EventHandlerProps } from '../MetaMaskProvider'; +import * as loggerModule from '../utils/logger'; jest.mock('@metamask/sdk', () => ({ ...jest.requireActual('@metamask/sdk'), @@ -9,6 +10,8 @@ jest.mock('@metamask/sdk', () => ({ })); describe('useHandleProviderEvent', () => { + const spyLogger = jest.spyOn(loggerModule, 'logger'); + const eventHandlerProps = { setConnected: jest.fn(), setConnecting: jest.fn(), @@ -29,12 +32,9 @@ describe('useHandleProviderEvent', () => { eventHandlerProps.setError = jest.fn(); eventHandlerProps.setChainId = jest.fn(); eventHandlerProps.setAccount = jest.fn(); - - console.debug = jest.fn(); }); it('should handle provider event correctly with debug enabled and TERMINATE type', () => { - eventHandlerProps.debug = true; const type = PROVIDER_UPDATE_TYPE.TERMINATE; const { result } = renderHook(() => @@ -42,8 +42,8 @@ describe('useHandleProviderEvent', () => { ); result.current(type); - expect(console.debug).toHaveBeenCalledWith( - `MetaMaskProvider::sdk on '${EventType.PROVIDER_UPDATE}' event.`, + expect(spyLogger).toHaveBeenCalledWith( + `[MetaMaskProvider: useHandleProviderEvent()] on '${EventType.PROVIDER_UPDATE}' event.`, type, ); expect(eventHandlerProps.setConnecting).toHaveBeenCalledWith(false); @@ -69,22 +69,6 @@ describe('useHandleProviderEvent', () => { ); }); - it('should handle provider event without debug logs', () => { - eventHandlerProps.debug = false; - const type = PROVIDER_UPDATE_TYPE.TERMINATE; - - const { result } = renderHook(() => - useHandleProviderEvent(eventHandlerProps), - ); - result.current(type); - - expect(console.debug).not.toHaveBeenCalled(); - expect(eventHandlerProps.setConnecting).toHaveBeenCalledWith(false); - expect(eventHandlerProps.setTrigger).toHaveBeenCalledWith( - expect.any(Function), - ); - }); - it('should increment the trigger value', () => { const type = PROVIDER_UPDATE_TYPE.TERMINATE; diff --git a/packages/sdk-react/src/EventsHandlers/useHandleSDKStatusEvent.test.tsx b/packages/sdk-react/src/EventsHandlers/useHandleSDKStatusEvent.test.tsx index bf63c9e8e..cb4ca1cb3 100644 --- a/packages/sdk-react/src/EventsHandlers/useHandleSDKStatusEvent.test.tsx +++ b/packages/sdk-react/src/EventsHandlers/useHandleSDKStatusEvent.test.tsx @@ -2,8 +2,11 @@ import { renderHook } from '@testing-library/react-hooks'; import { useHandleSDKStatusEvent } from './useHandleSDKStatusEvent'; import { EventType } from '@metamask/sdk'; import { EventHandlerProps } from '../MetaMaskProvider'; +import * as loggerModule from '../utils/logger'; describe('handleSDKStatusEvent', () => { + const spyLogger = jest.spyOn(loggerModule, 'logger'); + const eventHandlerProps = { setStatus: jest.fn(), } as unknown as EventHandlerProps; @@ -12,12 +15,9 @@ describe('handleSDKStatusEvent', () => { jest.clearAllMocks(); eventHandlerProps.setStatus = jest.fn(); - - console.debug = jest.fn(); }); it('should handle SDK status event correctly with debug enabled', () => { - eventHandlerProps.debug = true; const mockServiceStatus = { connectionStatus: 'connected', } as any; @@ -25,27 +25,13 @@ describe('handleSDKStatusEvent', () => { const { result } = renderHook(() => useHandleSDKStatusEvent(eventHandlerProps), ); + result.current(mockServiceStatus); - expect(console.debug).toHaveBeenCalledWith( - `MetaMaskProvider::sdk on '${EventType.SERVICE_STATUS}/${mockServiceStatus.connectionStatus}' event.`, + expect(spyLogger).toHaveBeenCalledWith( + `[MetaMaskProvider: useHandleSDKStatusEvent()] on '${EventType.SERVICE_STATUS}/${mockServiceStatus.connectionStatus}' event.`, mockServiceStatus, ); expect(eventHandlerProps.setStatus).toHaveBeenCalledWith(mockServiceStatus); }); - - it('should handle SDK status event without debug logs', () => { - eventHandlerProps.debug = false; - const mockServiceStatus = { - connectionStatus: 'connected', - } as any; - - const { result } = renderHook(() => - useHandleSDKStatusEvent(eventHandlerProps), - ); - result.current(mockServiceStatus); - - expect(console.debug).not.toHaveBeenCalled(); - expect(eventHandlerProps.setStatus).toHaveBeenCalledWith(mockServiceStatus); - }); }); diff --git a/packages/sdk-react/src/MetaMaskProvider.spec.tsx b/packages/sdk-react/src/MetaMaskProvider.spec.tsx index 9e4a3eb2a..8dc985e96 100644 --- a/packages/sdk-react/src/MetaMaskProvider.spec.tsx +++ b/packages/sdk-react/src/MetaMaskProvider.spec.tsx @@ -9,10 +9,13 @@ import { } from '@metamask/sdk'; import MetaMaskProvider, { SDKContext } from './MetaMaskProvider'; import { EthereumRpcError } from 'eth-rpc-errors'; +import * as loggerModule from './utils/logger'; jest.mock('@metamask/sdk'); describe('MetaMaskProvider Component', () => { + const spyLogger = jest.spyOn(loggerModule, 'logger'); + const mockMetaMaskSDK = MetaMaskSDK as jest.MockedClass; const initMock = jest.fn().mockResolvedValue(true); @@ -169,9 +172,8 @@ describe('MetaMaskProvider Component', () => { expect(initMock).toHaveBeenCalledTimes(1); }); - it('should print debug logs when debug is true', async () => { - const consoleSpy = jest.spyOn(console, 'debug').mockImplementation(); + it('should print debug logs', async () => { await act(async () => { render( { ); }); - expect(consoleSpy).toHaveBeenCalled(); - expect(consoleSpy.mock.calls[0][0]).toContain( - '[MetamaskProvider] init SDK Provider listeners', + expect(spyLogger).toHaveBeenCalled(); + expect(spyLogger.mock.calls[0][0]).toContain( + '[MetaMaskProviderClient] init SDK Provider listeners', ); - - consoleSpy.mockRestore(); }); it('should not print debug logs when debug is false or undefined', () => { diff --git a/packages/sdk/src/PostMessageStream/RemoteCommunicationPostMessageStream.test.ts b/packages/sdk/src/PostMessageStream/RemoteCommunicationPostMessageStream.test.ts index 06827a54d..2fdb58ff3 100644 --- a/packages/sdk/src/PostMessageStream/RemoteCommunicationPostMessageStream.test.ts +++ b/packages/sdk/src/PostMessageStream/RemoteCommunicationPostMessageStream.test.ts @@ -22,7 +22,6 @@ describe('RemoteCommunicationPostMessageStream', () => { name: ProviderConstants.PROVIDER, remote: mockRemoteCommunication, platformManager: mockPlatformManager, - debug: false, }); }); @@ -30,7 +29,6 @@ describe('RemoteCommunicationPostMessageStream', () => { expect(instance.state._name).toBe(ProviderConstants.PROVIDER); expect(instance.state.remote).toBe(mockRemoteCommunication); expect(instance.state.platformManager).toBe(mockPlatformManager); - expect(instance.state.debug).toBe(false); expect(mockRemoteCommunication.on).toHaveBeenCalledWith( EventType.MESSAGE, expect.any(Function), diff --git a/packages/sdk/src/PostMessageStream/getPostMessageStream.test.ts b/packages/sdk/src/PostMessageStream/getPostMessageStream.test.ts index e92a03fce..e5cb699fe 100644 --- a/packages/sdk/src/PostMessageStream/getPostMessageStream.test.ts +++ b/packages/sdk/src/PostMessageStream/getPostMessageStream.test.ts @@ -53,7 +53,6 @@ describe('getPostMessageStream', () => { name: ProviderConstants.CONTENT_SCRIPT, remote: fakeConnector, platformManager: fakePlatformManager, - debug: false, }); }); }); diff --git a/packages/sdk/src/provider/SDKProvider.test.ts b/packages/sdk/src/provider/SDKProvider.test.ts index 27e2af3e1..840231c44 100644 --- a/packages/sdk/src/provider/SDKProvider.test.ts +++ b/packages/sdk/src/provider/SDKProvider.test.ts @@ -40,7 +40,6 @@ describe('SDKProvider', () => { const sdkProviderProps: SDKProviderProps = { connectionStream: mockStream, shouldSendMetadata: false, - debug: true, autoRequestAccounts: false, }; @@ -49,10 +48,6 @@ describe('SDKProvider', () => { }); describe('Initialization', () => { - it('should set debug mode correctly', () => { - expect(provider.state.debug).toBe(true); - }); - it('should set autoRequestAccounts correctly', () => { expect(provider.state.autoRequestAccounts).toBe(false); }); diff --git a/packages/sdk/src/provider/wrapExtensionProvider.test.ts b/packages/sdk/src/provider/wrapExtensionProvider.test.ts index 37a5301cf..5d0765bc9 100644 --- a/packages/sdk/src/provider/wrapExtensionProvider.test.ts +++ b/packages/sdk/src/provider/wrapExtensionProvider.test.ts @@ -1,6 +1,7 @@ import { Duplex } from 'stream'; import { MetaMaskInpageProvider } from '@metamask/providers'; import { RPC_METHODS } from '../config'; +import * as loggerModule from '../utils/logger'; import { wrapExtensionProvider } from './wrapExtensionProvider'; jest.mock('stream', () => ({ @@ -33,6 +34,8 @@ function createMockExtensionProvider(): MetaMaskInpageProvider { } describe('wrapExtensionProvider', () => { + const spyLogger = jest.spyOn(loggerModule, 'logger'); + it('initializes Proxy around SDKProvider', () => { const provider = createMockExtensionProvider(); const wrapped = wrapExtensionProvider({ provider }); @@ -53,14 +56,15 @@ describe('wrapExtensionProvider', () => { }); it('logs debug information if debug flag is enabled', async () => { - const consoleSpy = jest.spyOn(console, 'debug'); const provider = createMockExtensionProvider(); - const wrapped = wrapExtensionProvider({ provider, debug: true }); + const wrapped = wrapExtensionProvider({ provider }); await wrapped.request({ method: 'someMethod' }); - expect(consoleSpy).toHaveBeenCalled(); - consoleSpy.mockRestore(); + expect(spyLogger).toHaveBeenCalledWith( + `[wrapExtensionProvider()] Overwriting request method`, + { method: 'someMethod' }, + ); }); it('handles special method correctly', async () => { diff --git a/packages/sdk/src/services/Analytics.test.ts b/packages/sdk/src/services/Analytics.test.ts index 54e155ac6..433e032c8 100644 --- a/packages/sdk/src/services/Analytics.test.ts +++ b/packages/sdk/src/services/Analytics.test.ts @@ -2,6 +2,7 @@ import { SendAnalytics, TrackingEvents, } from '@metamask/sdk-communication-layer'; +import * as loggerModule from '../utils/logger'; import { Analytics, AnalyticsProps } from './Analytics'; // Replace with your actual import path jest.mock('@metamask/sdk-communication-layer'); @@ -10,6 +11,7 @@ const mockSendAnalytics = SendAnalytics as jest.Mock; describe('Analytics', () => { let props: AnalyticsProps; + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); @@ -18,7 +20,6 @@ describe('Analytics', () => { props = { serverURL: 'https://test.server.url', - debug: false, metadata: { url: 'https://test.url', title: 'Test Title', @@ -38,7 +39,6 @@ describe('Analytics', () => { const customProps: AnalyticsProps = { ...props, enabled: true, - debug: true, }; const analytics = new Analytics(customProps); expect(analytics).toBeDefined(); @@ -67,27 +67,16 @@ describe('Analytics', () => { describe('Error Handling', () => { it('should log error when debug is true', async () => { - const consoleSpy = jest.spyOn(console, 'error').mockImplementation(); mockSendAnalytics.mockRejectedValue(new Error('Send failed')); - const analytics = new Analytics({ ...props, debug: true }); + const analytics = new Analytics({ ...props }); const event: TrackingEvents = TrackingEvents.AUTHORIZED; await analytics.send({ event }); - expect(consoleSpy).toHaveBeenCalled(); - }); - - it('should not log error when debug is false', async () => { - const consoleSpy = jest.spyOn(console, 'error').mockImplementation(); - mockSendAnalytics.mockRejectedValue(new Error('Send failed')); - - const analytics = new Analytics({ ...props, debug: false }); - const event: TrackingEvents = TrackingEvents.AUTHORIZED; - - await analytics.send({ event }); - - expect(consoleSpy).not.toHaveBeenCalled(); + expect(spyLogger).toHaveBeenCalledWith( + '[Analytics: send()] error: Error: Send failed', + ); }); }); }); diff --git a/packages/sdk/src/services/Ethereum.test.ts b/packages/sdk/src/services/Ethereum.test.ts index 08bcaf0f3..e89a7800e 100644 --- a/packages/sdk/src/services/Ethereum.test.ts +++ b/packages/sdk/src/services/Ethereum.test.ts @@ -20,7 +20,6 @@ describe('Ethereum Class', () => { connectionStream: stream, shouldSendMetadata: false, shouldShimWeb3: false, - debug: false, }; Ethereum.init(props); @@ -31,7 +30,6 @@ describe('Ethereum Class', () => { shouldSetOnWindow: false, shouldShimWeb3: false, autoRequestAccounts: false, - debug: false, }); expect(Ethereum.getInstance()).toBeDefined(); }); diff --git a/packages/sdk/src/services/MetaMaskInstaller/checkInstallation.test.ts b/packages/sdk/src/services/MetaMaskInstaller/checkInstallation.test.ts index 48186a7ae..d5878a185 100644 --- a/packages/sdk/src/services/MetaMaskInstaller/checkInstallation.test.ts +++ b/packages/sdk/src/services/MetaMaskInstaller/checkInstallation.test.ts @@ -1,33 +1,31 @@ import { MetaMaskInstaller } from '../../Platform/MetaMaskInstaller'; +import * as loggerModule from '../../utils/logger'; import { checkInstallation } from './checkInstallation'; describe('checkInstallation', () => { let instance: MetaMaskInstaller; const mockIsMetaMaskInstalled = jest.fn(); const mockRedirectToProperInstall = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); instance = { state: { - debug: false, platformManager: { isMetaMaskInstalled: mockIsMetaMaskInstalled }, }, redirectToProperInstall: mockRedirectToProperInstall, } as unknown as MetaMaskInstaller; }); - it('should log debug message when debug is enabled and MetaMask is installed', async () => { + it('should log debug message', async () => { mockIsMetaMaskInstalled.mockReturnValue(true); - const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(); - - instance.state.debug = true; await checkInstallation(instance); - expect(consoleLogSpy).toHaveBeenCalledWith( - 'MetamaskInstaller::checkInstallation() isInstalled=true', + expect(spyLogger).toHaveBeenCalledWith( + `[MetamaskInstaller: checkInstallation()] isInstalled=${true}`, ); }); diff --git a/packages/sdk/src/services/MetaMaskInstaller/redirectToProperInstall.test.ts b/packages/sdk/src/services/MetaMaskInstaller/redirectToProperInstall.test.ts index 900f909f4..c06f69fa5 100644 --- a/packages/sdk/src/services/MetaMaskInstaller/redirectToProperInstall.test.ts +++ b/packages/sdk/src/services/MetaMaskInstaller/redirectToProperInstall.test.ts @@ -1,5 +1,6 @@ import { PlatformType } from '@metamask/sdk-communication-layer'; import { MetaMaskInstaller } from '../../Platform/MetaMaskInstaller'; +import * as loggerModule from '../../utils/logger'; import { redirectToProperInstall } from './redirectToProperInstall'; describe('redirectToProperInstall', () => { @@ -7,6 +8,7 @@ describe('redirectToProperInstall', () => { const mockGetPlatformType = jest.fn(); const mockStartConnection = jest.fn(); const mockStartDesktopOnboarding = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); @@ -24,14 +26,12 @@ describe('redirectToProperInstall', () => { } as unknown as MetaMaskInstaller; }); - it('should log debug message when debug is enabled', async () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); + it('should log debug message', async () => { mockGetPlatformType.mockReturnValue(PlatformType.DesktopWeb); - instance.state.debug = true; await redirectToProperInstall(instance); - expect(consoleDebugSpy).toHaveBeenCalled(); + expect(spyLogger).toHaveBeenCalled(); }); it('should return false if platform is MetaMaskMobileWebview', async () => { diff --git a/packages/sdk/src/services/MetaMaskInstaller/startDesktopOnboarding.test.ts b/packages/sdk/src/services/MetaMaskInstaller/startDesktopOnboarding.test.ts index 890bedb22..7658a9017 100644 --- a/packages/sdk/src/services/MetaMaskInstaller/startDesktopOnboarding.test.ts +++ b/packages/sdk/src/services/MetaMaskInstaller/startDesktopOnboarding.test.ts @@ -1,6 +1,6 @@ import MetaMaskOnboarding from '@metamask/onboarding'; -import { MetaMaskInstaller } from '../../Platform/MetaMaskInstaller'; import { Ethereum } from '../Ethereum'; +import * as loggerModule from '../../utils/logger'; import { startDesktopOnboarding } from './startDesktopOnboarding'; jest.mock('@metamask/onboarding'); @@ -12,8 +12,7 @@ jest.mock('../Ethereum', () => ({ })); describe('startDesktopOnboarding', () => { - let instance: MetaMaskInstaller; - + const spyLogger = jest.spyOn(loggerModule, 'logger'); const mockMetaMaskOnboarding = MetaMaskOnboarding as jest.MockedClass< typeof MetaMaskOnboarding >; @@ -30,36 +29,27 @@ describe('startDesktopOnboarding', () => { } as unknown as MetaMaskOnboarding), ); - instance = { - state: { - debug: false, - }, - } as unknown as MetaMaskInstaller; - global.window = { ethereum: {}, } as any; }); it('should log debug message when debug is enabled', async () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - - await startDesktopOnboarding(instance); + await startDesktopOnboarding(); - expect(consoleDebugSpy).toHaveBeenCalledWith( - 'MetamaskInstaller::startDesktopOnboarding()', + expect(spyLogger).toHaveBeenCalledWith( + '[MetamaskInstaller: startDesktopOnboarding() starting desktop onboarding', ); }); it('should call Ethereum.destroy', async () => { - await startDesktopOnboarding(instance); + await startDesktopOnboarding(); expect(Ethereum.destroy).toHaveBeenCalled(); }); it('should delete window.ethereum', async () => { - await startDesktopOnboarding(instance); + await startDesktopOnboarding(); expect((window as any).ethereum).toBeUndefined(); }); @@ -67,7 +57,7 @@ describe('startDesktopOnboarding', () => { it('should call MetaMaskOnboarding.startOnboarding', async () => { mockStartOnboarding.mockImplementation(); - await startDesktopOnboarding(instance); + await startDesktopOnboarding(); expect(mockStartOnboarding).toHaveBeenCalled(); }); diff --git a/packages/sdk/src/services/MetaMaskInstaller/startInstaller.test.ts b/packages/sdk/src/services/MetaMaskInstaller/startInstaller.test.ts index 9fcf2b6af..dc5791b13 100644 --- a/packages/sdk/src/services/MetaMaskInstaller/startInstaller.test.ts +++ b/packages/sdk/src/services/MetaMaskInstaller/startInstaller.test.ts @@ -1,5 +1,6 @@ import { MetaMaskInstaller } from '../../Platform/MetaMaskInstaller'; import { wait as waitPromise } from '../../utils/wait'; +import * as loggerModule from '../../utils/logger'; import { startInstaller } from './startInstaller'; jest.mock('../../utils/wait', () => ({ @@ -9,6 +10,7 @@ jest.mock('../../utils/wait', () => ({ describe('startInstaller', () => { let instance: MetaMaskInstaller; const mockCheckInstallation = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); @@ -21,14 +23,11 @@ describe('startInstaller', () => { } as unknown as MetaMaskInstaller; }); - it('should log debug message when debug is enabled', async () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.state.debug = true; - + it('should log debug message', async () => { await startInstaller(instance, { wait: false }); - expect(consoleDebugSpy).toHaveBeenCalledWith( - 'MetamaskInstaller::start() wait=false', + expect(spyLogger).toHaveBeenCalledWith( + `[MetamaskInstaller: startInstaller()] wait=${false}`, ); }); diff --git a/packages/sdk/src/services/MetaMaskSDK/ConnectionManager/connect.test.ts b/packages/sdk/src/services/MetaMaskSDK/ConnectionManager/connect.test.ts index 128836cf1..1642f2a04 100644 --- a/packages/sdk/src/services/MetaMaskSDK/ConnectionManager/connect.test.ts +++ b/packages/sdk/src/services/MetaMaskSDK/ConnectionManager/connect.test.ts @@ -1,10 +1,12 @@ import { MetaMaskSDK } from '../../../sdk'; +import * as loggerModule from '../../../utils/logger'; import { connect } from './connect'; jest.mock('../../../sdk'); describe('connect', () => { let instance: MetaMaskSDK; + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); @@ -51,19 +53,14 @@ describe('connect', () => { describe('Debug Mode', () => { it('should log debug messages when debug is true', async () => { - instance.debug = true; - jest.spyOn(console, 'log').mockImplementation(); - jest.spyOn(console, 'debug').mockImplementation(); - await connect(instance); - expect(console.log).toHaveBeenCalledWith( - 'SDK::connect() provider not ready -- wait for init()', + expect(spyLogger).toHaveBeenCalledWith( + `[MetaMaskSDK: connect()] provider not ready -- wait for init()`, ); - expect(console.debug).toHaveBeenCalledWith( - 'SDK::connect()', - instance.activeProvider, + expect(spyLogger).toHaveBeenCalledWith( + `[MetaMaskSDK: connect()] activeProvider=${instance.activeProvider}`, ); }); }); diff --git a/packages/sdk/src/services/MetaMaskSDK/ConnectionManager/resume.test.ts b/packages/sdk/src/services/MetaMaskSDK/ConnectionManager/resume.test.ts index 8004cc017..1af244284 100644 --- a/packages/sdk/src/services/MetaMaskSDK/ConnectionManager/resume.test.ts +++ b/packages/sdk/src/services/MetaMaskSDK/ConnectionManager/resume.test.ts @@ -1,15 +1,18 @@ import { MetaMaskSDK } from '../../../sdk'; +import * as loggerModule from '../../../utils/logger'; import { resume } from './resume'; describe('resume', () => { let instance: MetaMaskSDK; let mockIsReady: jest.Mock; let mockStartConnection: jest.Mock; + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); mockIsReady = jest.fn(); mockStartConnection = jest.fn(); + spyLogger.mockImplementation(); instance = { debug: false, @@ -50,11 +53,12 @@ describe('resume', () => { it('should log debug messages when debug is true and getConnector().isReady is false', async () => { instance.debug = true; mockIsReady.mockReturnValue(false); - jest.spyOn(console, 'debug').mockImplementation(); await resume(instance); - expect(console.debug).toHaveBeenCalledWith('SDK::resume channel'); + expect(spyLogger).toHaveBeenCalledWith( + '[MetaMaskSDK: resume()] channel is not ready -- starting connection', + ); }); }); }); diff --git a/packages/sdk/src/services/MetaMaskSDK/ConnectionManager/terminate.test.ts b/packages/sdk/src/services/MetaMaskSDK/ConnectionManager/terminate.test.ts index 8736ca45a..0254524c3 100644 --- a/packages/sdk/src/services/MetaMaskSDK/ConnectionManager/terminate.test.ts +++ b/packages/sdk/src/services/MetaMaskSDK/ConnectionManager/terminate.test.ts @@ -2,6 +2,7 @@ import { EventType } from '@metamask/sdk-communication-layer'; import { STORAGE_PROVIDER_TYPE } from '../../../config'; import { MetaMaskSDK } from '../../../sdk'; import { PROVIDER_UPDATE_TYPE } from '../../../types/ProviderUpdateType'; +import * as loggerModule from '../../../utils/logger'; import { terminate } from './terminate'; describe('terminate', () => { @@ -10,6 +11,8 @@ describe('terminate', () => { const mockDisconnect = jest.fn(); const mockEmit = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'logger'); + const localStorageMock = { getItem: jest.fn(), setItem: jest.fn(), @@ -102,15 +105,11 @@ describe('terminate', () => { ); }); - it('should log debug messages when debug is true', () => { - instance.debug = true; - const consoleDebugSpy = jest - .spyOn(console, 'debug') - .mockImplementation(); + it('should log debug messages', () => { terminate(instance); - expect(consoleDebugSpy).toHaveBeenCalledWith( - 'SDK::terminate()', - instance.remoteConnection, + + expect(spyLogger).toHaveBeenCalledWith( + `[MetaMaskSDK: terminate()] remoteConnection=${instance.remoteConnection}`, ); }); diff --git a/packages/sdk/src/services/MetaMaskSDK/InitializerManager/setupAnalytics.test.ts b/packages/sdk/src/services/MetaMaskSDK/InitializerManager/setupAnalytics.test.ts index 7c0cc6392..8a724d3c2 100644 --- a/packages/sdk/src/services/MetaMaskSDK/InitializerManager/setupAnalytics.test.ts +++ b/packages/sdk/src/services/MetaMaskSDK/InitializerManager/setupAnalytics.test.ts @@ -51,14 +51,13 @@ describe('setupAnalytics', () => { name: 'DApp Name', }; instance.options._source = 'custom-source'; - instance.debug = true; + mockGetPlatformType.mockReturnValue('web'); await setupAnalytics(instance); expect(Analytics).toHaveBeenCalledWith({ serverURL: 'https://custom.server.url', - debug: true, metadata: { url: 'https://dapp.url', title: 'DApp Name', diff --git a/packages/sdk/src/services/MetaMaskSDK/ProviderManager/connectWithExtensionProvider.test.ts b/packages/sdk/src/services/MetaMaskSDK/ProviderManager/connectWithExtensionProvider.test.ts index 3f89868b9..43ca63620 100644 --- a/packages/sdk/src/services/MetaMaskSDK/ProviderManager/connectWithExtensionProvider.test.ts +++ b/packages/sdk/src/services/MetaMaskSDK/ProviderManager/connectWithExtensionProvider.test.ts @@ -2,6 +2,7 @@ import { EventType, TrackingEvents } from '@metamask/sdk-communication-layer'; import { MetaMaskSDK } from '../../../sdk'; import { PROVIDER_UPDATE_TYPE } from '../../../types/ProviderUpdateType'; import { STORAGE_PROVIDER_TYPE } from '../../../config'; +import * as loggerModule from '../../../utils/logger'; import { connectWithExtensionProvider } from './connectWithExtensionProvider'; jest.mock('../../../sdk'); @@ -11,7 +12,7 @@ describe('connectWithExtensionProvider', () => { const mockRequest: jest.Mock = jest.fn( () => new Promise((resolve) => setTimeout(resolve, 0)), ); - + const spyLogger = jest.spyOn(loggerModule, 'logger'); const mockSendAnalyticsEvent = jest.fn(); const mockLocalStorage = { @@ -73,23 +74,22 @@ describe('connectWithExtensionProvider', () => { await connectWithExtensionProvider(instance); - expect(consoleWarnSpy).toHaveBeenCalled(); + expect(consoleWarnSpy).toHaveBeenCalledWith( + `[MetaMaskSDK: connectWithExtensionProvider()] can't request accounts error`, + new Error('Some error'), + ); }); - it('should log debug information if instance.debug is true', async () => { - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - instance.debug = true; - + it('should log debug information', async () => { await connectWithExtensionProvider(instance); - expect(consoleDebugSpy).toHaveBeenCalledWith( - 'SDK::connectWithExtensionProvider()', + expect(spyLogger).toHaveBeenCalledWith( + '[MetaMaskSDK: connectWithExtensionProvider()] ', instance, ); - expect(consoleDebugSpy).toHaveBeenLastCalledWith( - 'SDK::connectWithExtensionProvider() accounts', - undefined, + expect(spyLogger).toHaveBeenLastCalledWith( + '[MetaMaskSDK: connectWithExtensionProvider()] accounts=undefined', ); }); diff --git a/packages/sdk/src/services/MetaMaskSDK/ProviderManager/connectWithExtensionProvider.ts b/packages/sdk/src/services/MetaMaskSDK/ProviderManager/connectWithExtensionProvider.ts index 97d0cea60..b7df5fe4f 100644 --- a/packages/sdk/src/services/MetaMaskSDK/ProviderManager/connectWithExtensionProvider.ts +++ b/packages/sdk/src/services/MetaMaskSDK/ProviderManager/connectWithExtensionProvider.ts @@ -37,7 +37,7 @@ export async function connectWithExtensionProvider(instance: MetaMaskSDK) { ); } catch (err) { // ignore error - logger( + console.warn( `[MetaMaskSDK: connectWithExtensionProvider()] can't request accounts error`, err, ); diff --git a/packages/sdk/src/services/PlatfformManager/isMetaMaskInstalled.test.ts b/packages/sdk/src/services/PlatfformManager/isMetaMaskInstalled.test.ts index cd609f39f..f72afc109 100644 --- a/packages/sdk/src/services/PlatfformManager/isMetaMaskInstalled.test.ts +++ b/packages/sdk/src/services/PlatfformManager/isMetaMaskInstalled.test.ts @@ -1,15 +1,14 @@ -import { PlatformManager } from '../../Platform/PlatfformManager'; import { Ethereum } from '../Ethereum'; +import * as loggerModule from '../../utils/logger'; import { isMetaMaskInstalled } from './isMetaMaskInstalled'; jest.mock('../Ethereum'); describe('isMetaMaskInstalled', () => { - let instance: jest.Mocked; - const mockEthereumGetProvider = Ethereum.getProvider as jest.MockedFunction< typeof Ethereum.getProvider >; + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); @@ -19,22 +18,15 @@ describe('isMetaMaskInstalled', () => { isConnected: () => false, } as any); - instance = { - state: { - debug: false, - }, - } as unknown as jest.Mocked; - global.window = {} as any; }); - it('should console debug when state.debug is true', () => { - instance.state.debug = true; - jest.spyOn(console, 'debug').mockImplementation(); + it('should console debug', () => { + isMetaMaskInstalled(); - isMetaMaskInstalled(instance); - - expect(console.debug).toHaveBeenCalled(); + expect(spyLogger).toHaveBeenCalledWith( + `[PlatfformManager: isMetaMaskInstalled()] isMetaMask=${false} isConnected=${false}`, + ); }); it('should return true when Ethereum.getProvider isMetaMask and isConnected are true', () => { @@ -43,7 +35,7 @@ describe('isMetaMaskInstalled', () => { isConnected: () => true, } as any); - expect(isMetaMaskInstalled(instance)).toBe(true); + expect(isMetaMaskInstalled()).toBe(true); }); it('should return false when Ethereum.getProvider isMetaMask is false', () => { @@ -52,7 +44,7 @@ describe('isMetaMaskInstalled', () => { isConnected: () => true, } as any); - expect(isMetaMaskInstalled(instance)).toBe(false); + expect(isMetaMaskInstalled()).toBe(false); }); it('should return false when Ethereum.getProvider isConnected is false', () => { @@ -61,7 +53,7 @@ describe('isMetaMaskInstalled', () => { isConnected: () => false, } as any); - expect(isMetaMaskInstalled(instance)).toBe(false); + expect(isMetaMaskInstalled()).toBe(false); }); it('should return true when window.ethereum isMetaMask and isConnected are true', () => { @@ -76,12 +68,12 @@ describe('isMetaMaskInstalled', () => { }, } as any; - expect(isMetaMaskInstalled(instance)).toBe(true); + expect(isMetaMaskInstalled()).toBe(true); }); it('should return false when neither Ethereum.getProvider nor window.ethereum exists', () => { global.window = {} as any; - expect(isMetaMaskInstalled(instance)).toBe(false); + expect(isMetaMaskInstalled()).toBe(false); }); }); diff --git a/packages/sdk/src/services/PlatfformManager/openDeeplink.test.ts b/packages/sdk/src/services/PlatfformManager/openDeeplink.test.ts index 73a4e2ce1..cce99dab9 100644 --- a/packages/sdk/src/services/PlatfformManager/openDeeplink.test.ts +++ b/packages/sdk/src/services/PlatfformManager/openDeeplink.test.ts @@ -3,10 +3,12 @@ import { PlatformManager, LINK_OPEN_DELAY, } from '../../Platform/PlatfformManager'; +import * as loggerModule from '../../utils/logger'; import { openDeeplink } from './openDeeplink'; describe('openDeeplink', () => { let instance: jest.Mocked; + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); @@ -23,15 +25,47 @@ describe('openDeeplink', () => { } as unknown as jest.Mocked; }); - it('should console debug when state.debug is true', () => { - instance.state.debug = true; - jest.spyOn(console, 'debug').mockImplementation(() => { - // do nothing - }); + it('should open a universal link when state.useDeeplink is false', () => { + global.window = { open: jest.fn() } as any; + + openDeeplink(instance, 'universalLink', 'deeplink'); + + expect(global.window.open).toHaveBeenCalledWith('universalLink', '_blank'); + }); + + it('should close the window after LINK_OPEN_DELAY', () => { + const mockWin = { close: jest.fn() }; + global.window = { + open: jest.fn().mockReturnValue(mockWin), + } as any; + + openDeeplink(instance, 'universalLink', 'deeplink'); + + jest.advanceTimersByTime(LINK_OPEN_DELAY); + + expect(mockWin.close).toHaveBeenCalled(); + }); + + it('should log debug info', () => { + global.window = { + open: jest.fn().mockImplementation(() => { + throw new Error('failure'); + }), + } as any; openDeeplink(instance, 'universalLink', 'deeplink'); - expect(console.debug).toHaveBeenCalledTimes(2); + expect(spyLogger).toHaveBeenCalledWith( + '[PlatfformManager: openDeeplink()] universalLink --> universalLink', + ); + + expect(spyLogger).toHaveBeenCalledWith( + '[PlatfformManager: openDeeplink()] deepLink --> deeplink', + ); + + expect(spyLogger).toHaveBeenCalledWith( + '[PlatfformManager: openDeeplink()] open link now useDeepLink=false link=universalLink', + ); }); it('should call enableWakeLock when instance.isBrowser() is true', () => { @@ -62,27 +96,6 @@ describe('openDeeplink', () => { expect(global.window.open).toHaveBeenCalledWith('deeplink', '_blank'); }); - it('should open a universal link when state.useDeeplink is false', () => { - global.window = { open: jest.fn() } as any; - - openDeeplink(instance, 'universalLink', 'deeplink'); - - expect(global.window.open).toHaveBeenCalledWith('universalLink', '_blank'); - }); - - it('should close the window after LINK_OPEN_DELAY', () => { - const mockWin = { close: jest.fn() }; - global.window = { - open: jest.fn().mockReturnValue(mockWin), - } as any; - - openDeeplink(instance, 'universalLink', 'deeplink'); - - jest.advanceTimersByTime(LINK_OPEN_DELAY); - - expect(mockWin.close).toHaveBeenCalled(); - }); - it('should log an error if opening the link fails', () => { jest.spyOn(console, 'log').mockImplementation(() => { // do nothing @@ -97,7 +110,7 @@ describe('openDeeplink', () => { openDeeplink(instance, 'universalLink', 'deeplink'); expect(console.log).toHaveBeenCalledWith( - `Platform::openDeepLink() can't open link`, + "[PlatfformManager: openDeeplink()] can't open link", new Error('failure'), ); }); diff --git a/packages/sdk/src/services/RemoteCommunicationPostMessageStream/onMessage.test.ts b/packages/sdk/src/services/RemoteCommunicationPostMessageStream/onMessage.test.ts index 073c4352f..80e72c51e 100644 --- a/packages/sdk/src/services/RemoteCommunicationPostMessageStream/onMessage.test.ts +++ b/packages/sdk/src/services/RemoteCommunicationPostMessageStream/onMessage.test.ts @@ -1,9 +1,11 @@ import { RemoteCommunicationPostMessageStream } from '../../PostMessageStream/RemoteCommunicationPostMessageStream'; import { ProviderConstants } from '../../constants'; +import * as loggerModule from '../../utils/logger'; import { onMessage } from './onMessage'; describe('onMessage', () => { let instance: jest.Mocked; + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); @@ -22,14 +24,10 @@ describe('onMessage', () => { data: {}, }; - instance.state.debug = true; - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - onMessage(instance, message); - expect(consoleDebugSpy).toHaveBeenCalledWith( - '[RCPMS] _onMessage ', - message, + expect(spyLogger).toHaveBeenCalledWith( + `[RCPMS: onMessage()] message=${message}`, ); }); diff --git a/packages/sdk/src/services/RemoteCommunicationPostMessageStream/write.test.ts b/packages/sdk/src/services/RemoteCommunicationPostMessageStream/write.test.ts index 5d377df17..7fe08a900 100644 --- a/packages/sdk/src/services/RemoteCommunicationPostMessageStream/write.test.ts +++ b/packages/sdk/src/services/RemoteCommunicationPostMessageStream/write.test.ts @@ -1,6 +1,7 @@ import { Ethereum } from '../Ethereum'; // Adjust the import based on your project structure import { RemoteCommunicationPostMessageStream } from '../../PostMessageStream/RemoteCommunicationPostMessageStream'; // Adjust the import based on your project structure import { METHODS_TO_REDIRECT } from '../../config'; +import * as loggerModule from '../../utils/logger'; // Adjust the import based on your project structure import { write } from './write'; // Adjust the import based on your project structure import { extractMethod } from './extractMethod'; @@ -8,6 +9,7 @@ jest.mock('./extractMethod'); jest.mock('../Ethereum'); describe('write function', () => { + const spyLogger = jest.spyOn(loggerModule, 'logger'); const mockExtractMethod = extractMethod as jest.Mock; const mockEthereum = Ethereum.getProvider as jest.Mock; const mockIsReady = jest.fn(); @@ -95,31 +97,10 @@ describe('write function', () => { expect(callback).toHaveBeenCalledWith(); }); - it('should not warn when method is METAMASK_GETPROVIDERSTATE', async () => { - mockExtractMethod.mockReturnValue({ - method: 'metamask_getProviderState', - }); - mockGetChannelId.mockReturnValue(undefined); - mockRemoteCommunicationPostMessageStream.state.debug = true; - - const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation(); - - await write( - mockRemoteCommunicationPostMessageStream, - { jsonrpc: '2.0', method: 'metamask_getProviderState' }, - 'utf8', - callback, - ); - - expect(consoleWarnSpy).not.toHaveBeenCalled(); - }); - - it('should warn when method is not METAMASK_GETPROVIDERSTATE', async () => { + it('should log when method is not METAMASK_GETPROVIDERSTATE', async () => { mockExtractMethod.mockReturnValue({}); mockGetChannelId.mockReturnValue(undefined); - mockRemoteCommunicationPostMessageStream.state.debug = true; - const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation(); await write( mockRemoteCommunicationPostMessageStream, @@ -128,8 +109,8 @@ describe('write function', () => { callback, ); - expect(consoleWarnSpy).toHaveBeenCalledWith( - 'RPCMS::_write Invalid channel id -- undefined', + expect(spyLogger).toHaveBeenCalledWith( + '[RCPMS: write()] Invalid channel id -- undefined', ); }); }); @@ -158,7 +139,6 @@ describe('write function', () => { mockIsReady.mockReturnValue(true); mockIsConnected.mockReturnValue(false); mockGetChannelId.mockReturnValue('some_channel_id'); - const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation(); await write( @@ -169,33 +149,14 @@ describe('write function', () => { ); expect(consoleWarnSpy).toHaveBeenCalledWith( - "RCPMS::_write invalid socket status -- shouln't happen", - ); - }); - - it('should not warn if both ready and socketConnected are true', async () => { - mockIsReady.mockReturnValue(true); - mockIsConnected.mockReturnValue(true); - mockRemoteCommunicationPostMessageStream.state.debug = true; - - const consoleWarnSpy = jest.spyOn(console, 'warn').mockImplementation(); - - await write( - mockRemoteCommunicationPostMessageStream, - { jsonrpc: '2.0', method: 'some_method' }, - 'utf8', - callback, + `[RCPMS: _write()] invalid socket status -- shouldn't happen`, ); - - expect(consoleWarnSpy).not.toHaveBeenCalled(); }); it('should debug log if both ready and socketConnected are true', async () => { mockIsReady.mockReturnValue(true); mockIsConnected.mockReturnValue(true); - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - await write( mockRemoteCommunicationPostMessageStream, { jsonrpc: '2.0', method: 'some_method' }, @@ -203,8 +164,8 @@ describe('write function', () => { callback, ); - expect(consoleDebugSpy).toHaveBeenCalledWith( - "RCPMS::_write method metamask_getProviderState doesn't need redirect.", + expect(spyLogger).toHaveBeenCalledWith( + `[RCPMS: _write()] method metamask_getProviderState doesn't need redirect.`, ); }); }); @@ -275,24 +236,6 @@ describe('write function', () => { it('should log debug messages if debug is enabled', async () => { mockIsReady.mockReturnValue(true); mockIsConnected.mockReturnValue(true); - mockRemoteCommunicationPostMessageStream.state.debug = true; - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - - await write( - mockRemoteCommunicationPostMessageStream, - { jsonrpc: '2.0', method: 'some_method' }, - 'utf8', - callback, - ); - - expect(consoleDebugSpy).toHaveBeenCalled(); - }); - - it('should not log debug messages if debug is disabled', async () => { - mockIsReady.mockReturnValue(true); - mockIsConnected.mockReturnValue(true); - mockRemoteCommunicationPostMessageStream.state.debug = false; - const consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); await write( mockRemoteCommunicationPostMessageStream, @@ -301,7 +244,7 @@ describe('write function', () => { callback, ); - expect(consoleDebugSpy).not.toHaveBeenCalled(); + expect(spyLogger).toHaveBeenCalled(); }); }); }); diff --git a/packages/sdk/src/services/RemoteCommunicationPostMessageStream/write.ts b/packages/sdk/src/services/RemoteCommunicationPostMessageStream/write.ts index 4b3996cb9..94cc2af5c 100644 --- a/packages/sdk/src/services/RemoteCommunicationPostMessageStream/write.ts +++ b/packages/sdk/src/services/RemoteCommunicationPostMessageStream/write.ts @@ -71,7 +71,9 @@ export async function write( if (!socketConnected && isRemoteReady) { // Shouldn't happen -- needs to refresh - logger(`[RCPMS: _write()] invalid socket status -- shouln't happen`); + console.warn( + `[RCPMS: _write()] invalid socket status -- shouldn't happen`, + ); return callback(); } diff --git a/packages/sdk/src/services/RemoteConnection/ConnectionInitializer/initializeConnector.test.ts b/packages/sdk/src/services/RemoteConnection/ConnectionInitializer/initializeConnector.test.ts index 4b9d37aee..faee4cfe5 100644 --- a/packages/sdk/src/services/RemoteConnection/ConnectionInitializer/initializeConnector.test.ts +++ b/packages/sdk/src/services/RemoteConnection/ConnectionInitializer/initializeConnector.test.ts @@ -7,6 +7,7 @@ import { RemoteConnectionProps, RemoteConnectionState, } from '../RemoteConnection'; +import * as loggerModule from '../../../utils/logger'; import { initializeConnector } from './initializeConnector'; jest.mock('@metamask/sdk-communication-layer'); @@ -15,6 +16,7 @@ describe('initializeConnector', () => { let state: RemoteConnectionState; let options: RemoteConnectionProps; const mockRemoteCommunication = RemoteCommunication as unknown as jest.Mock; + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); @@ -78,13 +80,12 @@ describe('initializeConnector', () => { ); }); - it('should print debug messages when developerMode is true', () => { - state.developerMode = true; - jest.spyOn(console, 'debug').mockImplementation(); - + it('should print debug messages', () => { initializeConnector(state, options); - expect(console.debug).toHaveBeenCalled(); + expect(spyLogger).toHaveBeenCalledWith( + `[RemoteConnection: initializeConnector()] initialize connector`, + ); }); it('should handle when platformManager.getPlatformType() returns undefined', () => { diff --git a/packages/sdk/src/services/RemoteConnection/ConnectionManager/handleDisconnect.test.ts b/packages/sdk/src/services/RemoteConnection/ConnectionManager/handleDisconnect.test.ts index ea59bf2bd..e67525a43 100644 --- a/packages/sdk/src/services/RemoteConnection/ConnectionManager/handleDisconnect.test.ts +++ b/packages/sdk/src/services/RemoteConnection/ConnectionManager/handleDisconnect.test.ts @@ -2,6 +2,7 @@ import { DisconnectOptions } from '@metamask/sdk-communication-layer'; import { Ethereum } from '../../Ethereum'; import { RemoteConnectionState } from '../RemoteConnection'; +import * as loggerModule from '../../../utils/logger'; import { handleDisconnect } from './handleDisconnect'; jest.mock('../../Ethereum', () => ({ @@ -17,6 +18,7 @@ describe('handleDisconnect', () => { let options: DisconnectOptions; const mockDisconnect = jest.fn(); const mockUnmount = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { state = { @@ -36,19 +38,12 @@ describe('handleDisconnect', () => { }); it('should log debug message when developerMode is true', async () => { - const consoleSpy = jest.spyOn(console, 'debug').mockImplementation(() => { - // do nothing - }); - state.developerMode = true; - await handleDisconnect(state, options); - expect(consoleSpy).toHaveBeenCalledWith( - 'RemoteConnection::disconnect()', + expect(spyLogger).toHaveBeenCalledWith( + `[RemoteConnection: disconnect()]`, options, ); - - consoleSpy.mockRestore(); }); it('should call handleDisconnect on Ethereum provider when options.terminate is true', async () => { diff --git a/packages/sdk/src/services/RemoteConnection/ConnectionManager/startConnection.test.ts b/packages/sdk/src/services/RemoteConnection/ConnectionManager/startConnection.test.ts index 03e404c2c..03bcdfd16 100644 --- a/packages/sdk/src/services/RemoteConnection/ConnectionManager/startConnection.test.ts +++ b/packages/sdk/src/services/RemoteConnection/ConnectionManager/startConnection.test.ts @@ -4,6 +4,7 @@ import { RemoteConnectionProps, RemoteConnectionState, } from '../RemoteConnection'; +import * as loggerModule from '../../../utils/logger'; import { connectWithDeeplink } from './connectWithDeeplink'; import { connectWithModalInstaller } from './connectWithModalInstaller'; import { startConnection } from './startConnection'; @@ -32,6 +33,7 @@ describe('startConnection', () => { let state: RemoteConnectionState; let options: RemoteConnectionProps; + const spyLogger = jest.spyOn(loggerModule, 'logger'); const mockOriginatorSessionConnect = jest.fn(); const mockGenerateChannelIdConnect = jest.fn(); const mockGetKeyInfo = jest.fn(); @@ -76,13 +78,12 @@ describe('startConnection', () => { ); }); - it('should handle developer mode debug logs', async () => { - state.developerMode = true; + it('should log debug info', async () => { mockOriginatorSessionConnect.mockResolvedValue({}); await startConnection(state, options); - expect(console.debug).toHaveBeenCalled(); + expect(spyLogger).toHaveBeenCalled(); }); it('should establish socket connection by emitting connecting', async () => { diff --git a/packages/sdk/src/services/RemoteConnection/EventListeners/setupListeners.test.ts b/packages/sdk/src/services/RemoteConnection/EventListeners/setupListeners.test.ts index eae1d6098..c78c47278 100644 --- a/packages/sdk/src/services/RemoteConnection/EventListeners/setupListeners.test.ts +++ b/packages/sdk/src/services/RemoteConnection/EventListeners/setupListeners.test.ts @@ -4,6 +4,7 @@ import { RemoteConnectionProps, RemoteConnectionState, } from '../RemoteConnection'; +import * as loggerModule from '../../../utils/logger'; import { setupListeners } from './setupListeners'; jest.mock('../../Ethereum', () => ({ @@ -21,6 +22,7 @@ jest.mock('../../Ethereum', () => ({ describe('setupListeners', () => { let state: RemoteConnectionState; let options: RemoteConnectionProps; + const spyLogger = jest.spyOn(loggerModule, 'logger'); const mockConnectorOn = jest.fn(); const mockOnPendingModalDisconnect = jest.fn(); @@ -37,6 +39,8 @@ describe('setupListeners', () => { mockIsAuthorized.mockReturnValue(true); + spyLogger.mockImplementation(); + state = { connector: { on: mockConnectorOn, @@ -238,6 +242,7 @@ describe('setupListeners', () => { it('should handle error in AUTHORIZED event', async () => { const mockProvider = { + getState: jest.fn(), _setConnected: jest.fn(), forceInitializeState: jest .fn() diff --git a/packages/sdk/src/services/RemoteConnection/EventListeners/setupListeners.ts b/packages/sdk/src/services/RemoteConnection/EventListeners/setupListeners.ts index 9ee29f1b1..ee33602d3 100644 --- a/packages/sdk/src/services/RemoteConnection/EventListeners/setupListeners.ts +++ b/packages/sdk/src/services/RemoteConnection/EventListeners/setupListeners.ts @@ -104,6 +104,10 @@ export function setupListeners( await provider.forceInitializeState(); } catch (err) { + console.log( + '🟠 ~ file: setupListeners.ts:107 ~ state.connector.on ~ err:', + err, + ); // Ignore error if already initialized. // console.debug(`IGNORE ERROR`, err); } diff --git a/packages/sdk/src/services/RemoteConnection/ModalManager/showInstallModal.test.ts b/packages/sdk/src/services/RemoteConnection/ModalManager/showInstallModal.test.ts index 503daecb3..0772306f9 100644 --- a/packages/sdk/src/services/RemoteConnection/ModalManager/showInstallModal.test.ts +++ b/packages/sdk/src/services/RemoteConnection/ModalManager/showInstallModal.test.ts @@ -2,6 +2,7 @@ import { RemoteConnectionProps, RemoteConnectionState, } from '../RemoteConnection'; +import * as loggerModule from '../../../utils/logger'; import { showInstallModal } from './showInstallModal'; describe('showInstallModal', () => { @@ -9,6 +10,7 @@ describe('showInstallModal', () => { let options: RemoteConnectionProps; const mockInstallModalMount = jest.fn(); const mockModalsInstall = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); @@ -59,14 +61,6 @@ describe('showInstallModal', () => { it('should terminate the connection and possibly log the termination', () => { const link = 'http://example.com/terminate'; - const mockConsoleDebug = jest - .spyOn(console, 'debug') - .mockImplementation(() => { - // do nothing - }); - - state.developerMode = true; - showInstallModal(state, options, link); const terminateCall = mockModalsInstall.mock.calls[0][0] @@ -74,23 +68,10 @@ describe('showInstallModal', () => { terminateCall(); - expect(mockConsoleDebug).toHaveBeenCalledWith( - 'RemoteConnection::showInstallModal() terminate connection', + expect(spyLogger).toHaveBeenCalledWith( + '[RemoteConnection: showInstallModal() => terminate()] terminate connection', ); expect(options.sdk.terminate).toHaveBeenCalledTimes(1); - - mockConsoleDebug.mockClear(); - - state.developerMode = false; - - showInstallModal(state, options, link); - - terminateCall(); - - expect(mockConsoleDebug).not.toHaveBeenCalled(); - expect(options.sdk.terminate).toHaveBeenCalledTimes(2); - - mockConsoleDebug.mockRestore(); }); it('should call connectWithExtensionProvider and return false', () => { diff --git a/packages/sdk/src/services/SDKProvider/ChainManager/handleChainChanged.test.ts b/packages/sdk/src/services/SDKProvider/ChainManager/handleChainChanged.test.ts index 37a7bcb5c..c3ddaf47a 100644 --- a/packages/sdk/src/services/SDKProvider/ChainManager/handleChainChanged.test.ts +++ b/packages/sdk/src/services/SDKProvider/ChainManager/handleChainChanged.test.ts @@ -1,11 +1,13 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ import { SDKProvider } from '../../../provider/SDKProvider'; +import * as loggerModule from '../../../utils/logger'; import { handleChainChanged } from './handleChainChanged'; describe('handleChainChanged', () => { let mockSDKProvider: SDKProvider; const superHandleChainChanged: jest.Mock = jest.fn(); const mockEmit: jest.Mock = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); @@ -20,23 +22,20 @@ describe('handleChainChanged', () => { }); it('should log debug information when debug is true', () => { - jest.spyOn(console, 'debug').mockImplementation(); handleChainChanged({ instance: mockSDKProvider, chainId: '1', superHandleChainChanged, }); - expect(console.debug).not.toHaveBeenCalled(); - mockSDKProvider.state.debug = true; handleChainChanged({ instance: mockSDKProvider, chainId: '1', superHandleChainChanged, }); - expect(console.debug).toHaveBeenCalledWith( - 'SDKProvider::_handleChainChanged chainId=1 networkVersion=undefined', + expect(spyLogger).toHaveBeenCalledWith( + `[SDKProvider: handleChainChanged()] chainId=${1} networkVersion=${undefined}`, ); }); diff --git a/packages/sdk/src/services/SDKProvider/ConnectionManager/handleDisconnect.test.ts b/packages/sdk/src/services/SDKProvider/ConnectionManager/handleDisconnect.test.ts index 5dc907c72..4e7694eeb 100644 --- a/packages/sdk/src/services/SDKProvider/ConnectionManager/handleDisconnect.test.ts +++ b/packages/sdk/src/services/SDKProvider/ConnectionManager/handleDisconnect.test.ts @@ -1,6 +1,7 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ import { ethErrors } from 'eth-rpc-errors'; import { SDKProvider } from '../../../provider/SDKProvider'; +import * as loggerModule from '../../../utils/logger'; import { handleDisconnect } from './handleDisconnect'; describe('handleDisconnect', () => { @@ -8,13 +9,13 @@ describe('handleDisconnect', () => { const mockEmit: jest.Mock = jest.fn(); const mockHandleAccountsChanged: jest.Mock = jest.fn(); const mockIsConnected: jest.Mock = jest.fn(() => true); + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); mockSDKProvider = { state: { - debug: false, providerStateRequested: true, }, _state: { @@ -32,18 +33,12 @@ describe('handleDisconnect', () => { } as unknown as SDKProvider; }); - it('should log debug information when debug is true', () => { + it('should log debug information', () => { jest.spyOn(console, 'debug').mockImplementation(); handleDisconnect({ terminate: false, instance: mockSDKProvider }); - expect(console.debug).not.toHaveBeenCalled(); - - mockSDKProvider.state.debug = true; - - handleDisconnect({ terminate: false, instance: mockSDKProvider }); - - expect(console.debug).toHaveBeenCalledWith( - 'SDKProvider::handleDisconnect() cleaning up provider state terminate=false', + expect(spyLogger).toHaveBeenCalledWith( + '[SDKProvider: handleDisconnect()] cleaning up provider state terminate=false', mockSDKProvider, ); }); @@ -91,40 +86,30 @@ describe('handleDisconnect', () => { expect(mockHandleAccountsChanged).toHaveBeenCalledWith([]); }); - it('should interrupt disconnection and log when not connected and debug is true', () => { + it('should interrupt disconnection and log when not connected', () => { mockIsConnected.mockReturnValueOnce(false); - mockSDKProvider.state.debug = true; - const spyConsoleDebug = jest.spyOn(console, 'debug').mockImplementation(); handleDisconnect({ terminate: false, instance: mockSDKProvider }); - expect(spyConsoleDebug).toHaveBeenCalledWith( - 'SDKProvider::handleDisconnect() not connected --- interrup disconnection', + expect(spyLogger).toHaveBeenCalledWith( + '[SDKProvider: handleDisconnect()] not connected --- interrupt disconnection', ); expect(mockSDKProvider.chainId).toBe('someChainId'); // @ts-ignore expect(mockSDKProvider._state.isConnected).toBe(true); expect(mockEmit).not.toHaveBeenCalled(); - - spyConsoleDebug.mockRestore(); }); - it('should interrupt disconnection and not log when not connected and debug is false', () => { + it('should interrupt disconnection', () => { mockIsConnected.mockReturnValueOnce(false); - mockSDKProvider.state.debug = false; - const spyConsoleDebug = jest.spyOn(console, 'debug').mockImplementation(); handleDisconnect({ terminate: false, instance: mockSDKProvider }); - expect(spyConsoleDebug).not.toHaveBeenCalled(); - expect(mockSDKProvider.chainId).toBe('someChainId'); // @ts-ignore expect(mockSDKProvider._state.isConnected).toBe(true); expect(mockEmit).not.toHaveBeenCalled(); - - spyConsoleDebug.mockRestore(); }); it('should not interrupt disconnection when connected', () => { diff --git a/packages/sdk/src/services/SDKProvider/ConnectionManager/handleDisconnect.ts b/packages/sdk/src/services/SDKProvider/ConnectionManager/handleDisconnect.ts index c9de47797..efaf8380f 100644 --- a/packages/sdk/src/services/SDKProvider/ConnectionManager/handleDisconnect.ts +++ b/packages/sdk/src/services/SDKProvider/ConnectionManager/handleDisconnect.ts @@ -28,7 +28,7 @@ export function handleDisconnect({ const connected = instance.isConnected(); if (!connected) { logger( - `[SDKProvider: handleDisconnect()] not connected --- interrup disconnection`, + `[SDKProvider: handleDisconnect()] not connected --- interrupt disconnection`, ); return; } diff --git a/packages/sdk/src/services/SDKProvider/InitializationManager/initializeState.test.ts b/packages/sdk/src/services/SDKProvider/InitializationManager/initializeState.test.ts index ec217fe96..e44b78bf6 100644 --- a/packages/sdk/src/services/SDKProvider/InitializationManager/initializeState.test.ts +++ b/packages/sdk/src/services/SDKProvider/InitializationManager/initializeState.test.ts @@ -1,10 +1,12 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ import { SDKProvider } from '../../../provider/SDKProvider'; +import * as loggerModule from '../../../utils/logger'; import { initializeState } from './initializeState'; describe('initializeState', () => { let mockSDKProvider: SDKProvider; const mockSuperInitializeState: jest.Mock = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); @@ -23,14 +25,8 @@ describe('initializeState', () => { jest.spyOn(console, 'debug').mockImplementation(); initializeState(mockSDKProvider, mockSuperInitializeState); - expect(console.debug).not.toHaveBeenCalled(); - - mockSDKProvider.state.debug = true; - - initializeState(mockSDKProvider, mockSuperInitializeState); - - expect(console.debug).toHaveBeenCalledWith( - 'SDKProvider::_initializeState() set state._initialized to false', + expect(spyLogger).toHaveBeenCalledWith( + '[SDKProvider: initializeState()] set state._initialized to false', ); }); diff --git a/packages/sdk/src/services/SDKProvider/InitializationManager/initializeStateAsync.test.ts b/packages/sdk/src/services/SDKProvider/InitializationManager/initializeStateAsync.test.ts index 553d7bf46..5e66283be 100644 --- a/packages/sdk/src/services/SDKProvider/InitializationManager/initializeStateAsync.test.ts +++ b/packages/sdk/src/services/SDKProvider/InitializationManager/initializeStateAsync.test.ts @@ -1,5 +1,6 @@ /* eslint-disable @typescript-eslint/ban-ts-comment */ import { SDKProvider } from '../../../provider/SDKProvider'; +import * as loggerModule from '../../../utils/logger'; import { initializeStateAsync } from './initializeStateAsync'; describe('initializeStateAsync', () => { @@ -7,14 +8,13 @@ describe('initializeStateAsync', () => { const mockRequest: jest.Mock = jest.fn(); const mockLogError: jest.Mock = jest.fn(); const mockInitializeState: jest.Mock = jest.fn(); + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); mockSDKProvider = { - state: { - debug: false, - }, + state: {}, providerStateRequested: false, request: mockRequest, _initializeState: mockInitializeState, @@ -22,19 +22,16 @@ describe('initializeStateAsync', () => { } as unknown as SDKProvider; }); - it('should log debug information when debug is true', async () => { - jest.spyOn(console, 'debug').mockImplementation(); - + it('should log debug information', async () => { await initializeStateAsync(mockSDKProvider as SDKProvider); - expect(console.debug).not.toHaveBeenCalled(); - - // eslint-disable-next-line require-atomic-updates - mockSDKProvider.state.debug = true; - await initializeStateAsync(mockSDKProvider as SDKProvider); + expect(spyLogger).toHaveBeenCalledWith( + `[SDKProvider: initializeStateAsync()] initialize state async started`, + ); - expect(console.debug).toHaveBeenCalledWith( - `SDKProvider::_initializeStateAsync()`, + expect(spyLogger).toHaveBeenCalledWith( + '[SDKProvider: initializeStateAsync()] state selectedAddress=undefined ', + undefined, ); }); @@ -128,14 +125,12 @@ describe('initializeStateAsync', () => { }); it('should log debug information for different scenarios', async () => { - jest.spyOn(console, 'debug').mockImplementation(); - mockSDKProvider.state.debug = true; const mockInitialState = { accounts: [] }; mockRequest.mockResolvedValue(mockInitialState); await initializeStateAsync(mockSDKProvider as SDKProvider); - expect(console.debug).toHaveBeenCalledWith( + expect(spyLogger).toHaveBeenCalledWith( expect.stringContaining("initial state doesn't contain accounts"), ); }); diff --git a/packages/sdk/src/ui/InstallModal/InstallModal-nodejs.test.ts b/packages/sdk/src/ui/InstallModal/InstallModal-nodejs.test.ts index 92421b25d..795487a71 100644 --- a/packages/sdk/src/ui/InstallModal/InstallModal-nodejs.test.ts +++ b/packages/sdk/src/ui/InstallModal/InstallModal-nodejs.test.ts @@ -1,4 +1,5 @@ import { generate } from 'qrcode-terminal-nooctal'; +import * as loggerModule from '../../utils/logger'; import InstallModal from './InstallModal-nodejs'; jest.mock('qrcode-terminal-nooctal', () => ({ @@ -6,12 +7,12 @@ jest.mock('qrcode-terminal-nooctal', () => ({ })); describe('InstallModal-nodejs', () => { - let consoleLogSpy: jest.SpyInstance; + const spyLogger = jest.spyOn(loggerModule, 'logger'); + const mockGenerate = generate as jest.Mock; beforeEach(() => { jest.clearAllMocks(); - consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(); global.document = { createElement: jest.fn(), @@ -33,18 +34,13 @@ describe('InstallModal-nodejs', () => { ); }); - it('should log the QR code to the console', () => { - InstallModal({ link: 'http://example.com' }); - - expect(consoleLogSpy).toHaveBeenCalledWith('Mocked QR Code'); - }); - - it('should log the QR code URL to the console', () => { - const mockLink = 'http://example.com'; - - InstallModal({ link: mockLink }); + it('should log the QR code link', () => { + const link = 'http://example.com'; + InstallModal({ link }); - expect(consoleLogSpy).toHaveBeenCalledWith('qrcode url: ', mockLink); + expect(spyLogger).toHaveBeenCalledWith( + `[UI: InstallModal-nodejs()] qrcode url: ${link}`, + ); }); it('should return an object with unmount function', () => { diff --git a/packages/sdk/src/ui/InstallModal/InstallModal-nonweb.test.ts b/packages/sdk/src/ui/InstallModal/InstallModal-nonweb.test.ts index 7ea29e8e9..686a483f9 100644 --- a/packages/sdk/src/ui/InstallModal/InstallModal-nonweb.test.ts +++ b/packages/sdk/src/ui/InstallModal/InstallModal-nonweb.test.ts @@ -1,11 +1,12 @@ +import * as loggerModule from '../../utils/logger'; import InstallModal from './InstallModal-nonweb'; describe('InstallModal-nonweb', () => { - let consoleLogSpy: jest.SpyInstance; + let logger: jest.SpyInstance; beforeEach(() => { jest.clearAllMocks(); - consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(); + logger = jest.spyOn(loggerModule, 'logger').mockImplementation(); }); it('should log INSTALL MODAL along with the link', () => { @@ -13,7 +14,9 @@ describe('InstallModal-nonweb', () => { InstallModal({ link: mockLink }); - expect(consoleLogSpy).toHaveBeenCalledWith('INSTALL MODAL', mockLink); + expect(logger).toHaveBeenCalledWith( + `[UI: InstallModal-nonweb()] INSTALL MODAL link=${mockLink}`, + ); }); it('should return an object with unmount function', () => { diff --git a/packages/sdk/src/ui/InstallModal/InstallModal-web.test.ts b/packages/sdk/src/ui/InstallModal/InstallModal-web.test.ts index 0ed537c55..870ca4b29 100644 --- a/packages/sdk/src/ui/InstallModal/InstallModal-web.test.ts +++ b/packages/sdk/src/ui/InstallModal/InstallModal-web.test.ts @@ -1,5 +1,6 @@ import { ModalLoader } from '@metamask/sdk-install-modal-web'; import { i18n } from 'i18next'; +import * as loggerModule from '../../utils/logger'; import sdkWebInstallModal from './InstallModal-web'; jest.mock('@metamask/sdk-install-modal-web'); @@ -8,7 +9,8 @@ jest.mock('i18next', () => ({ })); describe('sdkWebInstallModal', () => { - let consoleDebugSpy: jest.SpyInstance; + const spyLogger = jest.spyOn(loggerModule, 'logger'); + let documentSpy: jest.SpyInstance; let mockI18n: i18n = { t: jest.fn((key) => key), @@ -27,8 +29,6 @@ describe('sdkWebInstallModal', () => { mockModalLoader.mockImplementation(() => modalLoaderMock as any); - consoleDebugSpy = jest.spyOn(console, 'debug').mockImplementation(); - mockI18n = { t: jest.fn((key) => key), } as unknown as i18n; @@ -61,7 +61,7 @@ describe('sdkWebInstallModal', () => { expect(global.document.body.appendChild).toHaveBeenCalled(); }); - it('should log debug information if debug is true', () => { + it('should log debug information', () => { sdkWebInstallModal({ link: 'http://example.com', debug: true, @@ -69,7 +69,7 @@ describe('sdkWebInstallModal', () => { i18nInstance: mockI18n, }); - expect(consoleDebugSpy).toHaveBeenCalled(); + expect(spyLogger).toHaveBeenCalled(); }); it('should call renderSelectModal if window.extension exists', () => { @@ -179,9 +179,7 @@ describe('sdkWebInstallModal', () => { expect(divMock.parentNode.removeChild).toHaveBeenCalledWith(divMock); }); - it('should log debug information if debug is true', () => { - const consoleInfoSpy = jest.spyOn(console, 'info').mockImplementation(); - + it('should log debug information', () => { const { unmount } = sdkWebInstallModal({ link: 'http://example.com', debug: true, @@ -191,7 +189,7 @@ describe('sdkWebInstallModal', () => { unmount(); - expect(consoleInfoSpy).toHaveBeenCalled(); + expect(spyLogger).toHaveBeenCalled(); }); it('should call terminate if shouldTerminate is true', () => { diff --git a/packages/sdk/src/ui/InstallModal/pendingModal-nodejs.test.ts b/packages/sdk/src/ui/InstallModal/pendingModal-nodejs.test.ts index c1be67a04..befca10a4 100644 --- a/packages/sdk/src/ui/InstallModal/pendingModal-nodejs.test.ts +++ b/packages/sdk/src/ui/InstallModal/pendingModal-nodejs.test.ts @@ -1,21 +1,18 @@ +import * as loggerModule from '../../utils/logger'; import PendingModal from './pendingModal-nodejs'; describe('PendingModal', () => { - let consoleLogSpy: jest.SpyInstance; - let consoleInfoSpy: jest.SpyInstance; + const spyLogger = jest.spyOn(loggerModule, 'logger'); beforeEach(() => { jest.clearAllMocks(); - - consoleLogSpy = jest.spyOn(console, 'log').mockImplementation(); - consoleInfoSpy = jest.spyOn(console, 'info').mockImplementation(); }); it('should log initial message upon invocation', () => { PendingModal(); - expect(consoleLogSpy).toHaveBeenCalledWith( - 'Please open the MetaMask wallet app and confirm the connection. Thank you!', + expect(spyLogger).toHaveBeenCalledWith( + '[UI: pendingModal-nodejs: PendingModal()] Please open the MetaMask wallet app and confirm the connection. Thank you!', ); }); @@ -36,8 +33,8 @@ describe('PendingModal', () => { result.updateOTPValue(otpValue); - expect(consoleInfoSpy).toHaveBeenCalledWith( - `Choose the following value on your metamask mobile wallet: ${otpValue}`, + expect(spyLogger).toHaveBeenCalledWith( + '[UI: pendingModal-nodejs: PendingModal()] Choose the following value on your metamask mobile wallet: 123456', ); }); @@ -46,7 +43,9 @@ describe('PendingModal', () => { result.updateOTPValue(''); - expect(consoleInfoSpy).not.toHaveBeenCalled(); + expect(spyLogger).toHaveBeenCalledWith( + '[UI: pendingModal-nodejs: PendingModal()] Please open the MetaMask wallet app and confirm the connection. Thank you!', + ); }); describe('mount()', () => { @@ -55,8 +54,8 @@ describe('PendingModal', () => { result.mount(); - expect(consoleLogSpy).toHaveBeenCalledWith( - 'Please open the MetaMask wallet app and confirm the connection. Thank you!', + expect(spyLogger).toHaveBeenCalledWith( + '[UI: pendingModal-nodejs: PendingModal()] Please open the MetaMask wallet app and confirm the connection. Thank you!', ); }); }); @@ -67,8 +66,8 @@ describe('PendingModal', () => { result.unmount(); - expect(consoleLogSpy).toHaveBeenCalledWith( - 'Please open the MetaMask wallet app and confirm the connection. Thank you!', + expect(spyLogger).toHaveBeenCalledWith( + '[UI: pendingModal-nodejs: PendingModal()] Please open the MetaMask wallet app and confirm the connection. Thank you!', ); }); }); @@ -80,8 +79,8 @@ describe('PendingModal', () => { result.updateOTPValue(otpValue); - expect(consoleInfoSpy).toHaveBeenCalledWith( - `Choose the following value on your metamask mobile wallet: ${otpValue}`, + expect(spyLogger).toHaveBeenCalledWith( + '[UI: pendingModal-nodejs: PendingModal()] Choose the following value on your metamask mobile wallet: 123456', ); }); @@ -90,7 +89,9 @@ describe('PendingModal', () => { result.updateOTPValue(''); - expect(consoleInfoSpy).not.toHaveBeenCalled(); + expect(spyLogger).toHaveBeenCalledWith( + '[UI: pendingModal-nodejs: PendingModal()] Please open the MetaMask wallet app and confirm the connection. Thank you!', + ); }); }); });