diff --git a/package.json b/package.json index b9775c9..175510c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "notificationapi-js-client-sdk", - "version": "4.6.2", + "version": "4.6.3", "description": "NotificationAPI client-side library for JavaScript", "keywords": [ "notificationapi", diff --git a/src/__tests__/getUserPreferences.test.ts b/src/__tests__/getUserPreferences.test.ts index a20712d..7e5259c 100644 --- a/src/__tests__/getUserPreferences.test.ts +++ b/src/__tests__/getUserPreferences.test.ts @@ -35,6 +35,7 @@ describe('given connection is already open', () => { await server.connected; await server.nextMessage; // environment/data request }); + test('sends a user_preferences/preferences message', async () => { notificationapi.getUserPreferences(); const request: WS_UserPreferencesRequest = { @@ -98,14 +99,27 @@ describe('given connection is not open yet', () => { }); describe('given no websocket', () => { - test('rejects the promise', async () => { + test('rejects the promise when websocket is not present', async () => { notificationapi = new NotificationAPI({ clientId: '', userId: '', websocket: false }); - notificationapi.getUserPreferences().catch((error) => { - expect(error).toEqual('Websocket is not present.'); + await expect(notificationapi.getUserPreferences()).rejects.toEqual( + 'Websocket is not present.' + ); + }); + test('rejects the promise when websocket fails to open', async () => { + // Mocking a websocket connection that will not open + server.error(); // Simulate an error that prevents websocket from opening + notificationapi = new NotificationAPI({ + clientId, + userId, + websocket: 'ws://localhost:1235' }); + // Wait for the getUserPreferences method to be invoked and handle the rejection + await expect(notificationapi.getUserPreferences()).rejects.toEqual( + 'Websocket failed to open.' + ); }); }); diff --git a/src/index.ts b/src/index.ts index e769a4b..72e39ab 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1307,13 +1307,26 @@ class NotificationAPIClient implements NotificationAPIClientInterface { websocketOpened(): Promise { return new Promise((resolve, reject) => { - if (!this.websocket) reject('Websocket is not present.'); - else { - const ws = this.websocket; - if (ws.readyState == ws.OPEN) { + const ws = this.websocket; + if (!ws) { + reject('Websocket is not present.'); + return; + } + + const checkState = () => { + if (ws.readyState === ws.OPEN) { resolve(ws); + } else if ( + ws.readyState === ws.CLOSED || + ws.readyState === ws.CLOSING + ) { + reject('Websocket failed to open.'); + } else { + setTimeout(checkState, 100); // Check again in 100ms } - } + }; + + checkState(); }); } }