diff --git a/package-lock.json b/package-lock.json index 3951c58..e42cee2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,6 +25,7 @@ "@types/jasmine": "^3.9.1", "@typescript-eslint/eslint-plugin": "^3.10.1", "@typescript-eslint/parser": "^3.10.1", + "axios-mock-adapter": "^2.0.0", "eslint": "^7.32.0", "eslint-plugin-security": "^1.4.0", "istanbul-instrumenter-loader": "^3.0.1", @@ -4144,6 +4145,48 @@ "proxy-from-env": "^1.1.0" } }, + "node_modules/axios-mock-adapter": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/axios-mock-adapter/-/axios-mock-adapter-2.0.0.tgz", + "integrity": "sha512-D/K0J5Zm6KvaMTnsWrBQZWLzKN9GxUFZEa0mx2qeEHXDeTugCoplWehy8y36dj5vuSjhe1u/Dol8cZ8lzzmDew==", + "dev": true, + "dependencies": { + "fast-deep-equal": "^3.1.3", + "is-buffer": "^2.0.5" + }, + "peerDependencies": { + "axios": ">= 0.17.0" + } + }, + "node_modules/axios-mock-adapter/node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, + "node_modules/axios-mock-adapter/node_modules/is-buffer": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.5.tgz", + "integrity": "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "engines": { + "node": ">=4" + } + }, "node_modules/axios-retry": { "version": "3.9.1", "resolved": "https://registry.npmjs.org/axios-retry/-/axios-retry-3.9.1.tgz", @@ -16889,6 +16932,30 @@ "proxy-from-env": "^1.1.0" } }, + "axios-mock-adapter": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/axios-mock-adapter/-/axios-mock-adapter-2.0.0.tgz", + "integrity": "sha512-D/K0J5Zm6KvaMTnsWrBQZWLzKN9GxUFZEa0mx2qeEHXDeTugCoplWehy8y36dj5vuSjhe1u/Dol8cZ8lzzmDew==", + "dev": true, + "requires": { + "fast-deep-equal": "^3.1.3", + "is-buffer": "^2.0.5" + }, + "dependencies": { + "fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true + }, + "is-buffer": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.5.tgz", + "integrity": "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ==", + "dev": true + } + } + }, "axios-retry": { "version": "3.9.1", "resolved": "https://registry.npmjs.org/axios-retry/-/axios-retry-3.9.1.tgz", diff --git a/package.json b/package.json index 689c0eb..f12ea90 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "@types/jasmine": "^3.9.1", "@typescript-eslint/eslint-plugin": "^3.10.1", "@typescript-eslint/parser": "^3.10.1", + "axios-mock-adapter": "^2.0.0", "eslint": "^7.32.0", "eslint-plugin-security": "^1.4.0", "istanbul-instrumenter-loader": "^3.0.1", diff --git a/src/SDK.ts b/src/SDK.ts index 6ab4629..0a3b493 100644 --- a/src/SDK.ts +++ b/src/SDK.ts @@ -1,7 +1,8 @@ import * as hash from "crypto"; -import { ChannelId, LiveChatVersion, OCSDKTelemetryEvent } from "./Common/Enums"; +import { ChannelId, LiveChatVersion, OCSDKTelemetryEvent, SDKError } from "./Common/Enums"; import axios, { AxiosRequestConfig, AxiosResponse } from "axios"; + import { BrowserInfo } from "./Utils/BrowserInfo"; import Constants from "./Common/Constants"; import { CustomContextData } from "./Utils/CustomContextData"; @@ -39,14 +40,13 @@ import ReconnectMappingRecord from "./Model/ReconnectMappingRecord"; import { RequestTimeoutConfig } from "./Common/RequestTimeoutConfig"; import { StringMap } from "./Common/Mappings"; import { Timer } from "./Utils/Timer"; +import { addOcUserAgentHeader } from "./Utils/httpHeadersUtils"; import axiosRetryHandler from "./Utils/axiosRetryHandler"; import { createGetChatTokenEndpoint } from "./Utils/endpointsCreators"; import isExpectedAxiosError from "./Utils/isExpectedAxiosError"; import sessionInitRetryHandler from "./Utils/SessionInitRetryHandler"; -import throwClientHTTPTimeoutError from "./Utils/throwClientHTTPError"; import { uuidv4 } from "./Utils/uuid"; import { waitTimeBetweenRetriesConfigs } from "./Utils/waitTimeBetweenRetriesConfigs"; -import { addOcUserAgentHeader } from "./Utils/httpHeadersUtils"; export default class SDK implements ISDK { private static defaultRequestTimeoutConfig: RequestTimeoutConfig = { @@ -84,6 +84,8 @@ export default class SDK implements ISDK { liveChatVersion: number; sessionId?: string; ocUserAgent: string[]; + HTTPTimeOutErrorMessage = `${SDKError.ClientHTTPTimeoutErrorName}: ${SDKError.ClientHTTPTimeoutErrorMessage}`; + public constructor(private omnichannelConfiguration: IOmnichannelConfiguration, private configuration: ISDKConfiguration = SDK.defaultConfiguration, private logger?: OCSDKLogger) { // Sets to default configuration if passed configuration is empty or is not an object @@ -289,7 +291,7 @@ export default class SDK implements ISDK { const elapsedTimeInMilliseconds = timer.milliSecondsElapsed; this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.GETLWISTATUSFAILED, "Get LWI Details failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } reject(error); } @@ -380,6 +382,13 @@ export default class SDK implements ISDK { // Resolves only if it contains chat token response which only happens on status 200 if (data) { + + // check if data is empty, if so, then reject the promise + if (Object.keys(data).length === 0) { + reject(new Error("Empty data received from getChatToken")); + return; + } + data.requestId = requestId; this.logWithLogger(LogLevel.INFO, OCSDKTelemetryEvent.GETCHATTOKENSUCCEEDED, "Get Chat Token succeeded", requestId, response, elapsedTimeInMilliseconds, requestPath, method, undefined, undefined, requestHeaders); resolve(data); @@ -396,7 +405,7 @@ export default class SDK implements ISDK { const elapsedTimeInMilliseconds = timer.milliSecondsElapsed; this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.GETCHATTOKENFAILED, "Get Chat Token failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } reject(error); } @@ -453,7 +462,7 @@ export default class SDK implements ISDK { const elapsedTimeInMilliseconds = timer.milliSecondsElapsed; this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.GETRECONNECTABLECHATS, "Get Reconnectable Chats failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } reject(error); return; @@ -505,7 +514,7 @@ export default class SDK implements ISDK { const elapsedTimeInMilliseconds = timer.milliSecondsElapsed; this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.GETRECONNECTAVAILABILITY, "Get Reconnect Availability failed", undefined, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } reject(error); return; @@ -608,7 +617,7 @@ export default class SDK implements ISDK { this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.GETAGENTAVAILABILITYFAILED, "Get agent availability failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } reject(error); } @@ -708,8 +717,9 @@ export default class SDK implements ISDK { } catch (error) { const elapsedTimeInMilliseconds = timer.milliSecondsElapsed; this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.SESSIONINITFAILED, "Session Init failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, data, requestHeaders); + if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } reject(error); } @@ -781,7 +791,7 @@ export default class SDK implements ISDK { const elapsedTimeInMilliseconds = timer.milliSecondsElapsed; this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.SESSIONCLOSEFAILED, "Session close failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (error.code === Constants.axiosTimeoutErrorCode) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } reject(error); } @@ -848,7 +858,7 @@ export default class SDK implements ISDK { this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.VALIDATEAUTHCHATRECORDFAILED, "Validate Auth Chat Record failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } if (error.toString() === "Error: Request failed with status code 404") { // backward compatibility @@ -912,7 +922,7 @@ export default class SDK implements ISDK { const elapsedTimeInMilliseconds = timer.milliSecondsElapsed; this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.SUBMITPOSTCHATFAILED, "Submit Post Chat Failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } reject(error); } @@ -982,7 +992,7 @@ export default class SDK implements ISDK { const elapsedTimeInMilliseconds = timer.milliSecondsElapsed; this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.GETSURVEYINVITELINKFAILED, "Get Survey Invite Link failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } reject(error); } @@ -1049,10 +1059,12 @@ export default class SDK implements ISDK { this.logWithLogger(LogLevel.INFO, OCSDKTelemetryEvent.GETCHATTRANSCRIPTSUCCEEDED, "Get Chat Transcript succeeded", requestId, response, elapsedTimeInMilliseconds, requestPath, method, undefined, undefined, requestHeaders); resolve(data); } catch (error) { + const elapsedTimeInMilliseconds = timer.milliSecondsElapsed; this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.GETCHATTRANSCRIPTFAILED, "Get Chat Transcript failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject(new Error(this.HTTPTimeOutErrorMessage)); + } reject(error); } @@ -1116,7 +1128,7 @@ export default class SDK implements ISDK { const elapsedTimeInMilliseconds = timer.milliSecondsElapsed; this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.EMAILTRANSCRIPTFAILED, "Email Transcript Failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } reject(error); } @@ -1168,7 +1180,7 @@ export default class SDK implements ISDK { const elapsedTimeInMilliseconds = timer.milliSecondsElapsed; this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.FETCHDATAMASKINGFAILED, "Fetch Data Masking Failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } reject(error); } @@ -1231,7 +1243,7 @@ export default class SDK implements ISDK { const elapsedTimeInMilliseconds = timer.milliSecondsElapsed; this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.SECONDARYCHANNELEVENTREQUESTFAILED, "Secondary Channel Event Request Failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } reject(error); } @@ -1281,7 +1293,7 @@ export default class SDK implements ISDK { this.logWithLogger(LogLevel.ERROR, OCSDKTelemetryEvent.SENDTYPINGINDICATORFAILED, "Send Typing Indicator Failed", requestId, undefined, elapsedTimeInMilliseconds, requestPath, method, error, undefined, requestHeaders); if (isExpectedAxiosError(error, Constants.axiosTimeoutErrorCode)) { - throwClientHTTPTimeoutError(); + reject( new Error(this.HTTPTimeOutErrorMessage)); } reject(error); } diff --git a/test/SDK.spec.ts b/test/SDK.spec.ts index 3163bb5..6b21085 100644 --- a/test/SDK.spec.ts +++ b/test/SDK.spec.ts @@ -22,6 +22,7 @@ import ISubmitPostChatResponseOptionalParams from "../src/Interfaces/ISubmitPost import IValidateAuthChatRecordOptionalParams from "../src/Interfaces/IValidateAuthChatRecordOptionalParams"; import { LocationInfo } from "../src/Utils/LocationInfo"; import { LogLevel } from "../src/Model/LogLevel"; +import MockAdapter from 'axios-mock-adapter'; import OCSDKLogger from "../src/Common/OCSDKLogger"; import { OSInfo } from "../src/Utils/OSInfo"; import SDK from "../src/SDK"; @@ -40,6 +41,7 @@ describe("SDK unit tests", () => { let dataMock: any; let uuidvSpy: any; let axiosInstMock: any; + let axiosInstEmptyMock:any; let axiosInstMockWithError: any; let ocsdkLogger: any; const logger = { @@ -60,6 +62,7 @@ describe("SDK unit tests", () => { spyOn(axiosRetryHandler, "default").and.callFake(() => {}); axiosInstMock = jasmine.createSpy("axiosInstance").and.returnValue(dataMock); axiosInstMockWithError = jasmine.createSpy("axiosInstance").and.throwError(AxiosError); + axiosInstEmptyMock = jasmine.createSpy("axiosInstance").and.returnValue({data: {}}); }); describe("Test constructor", () => { @@ -206,7 +209,7 @@ describe("SDK unit tests", () => { const sdk = new SDK(ochannelConfig as IOmnichannelConfiguration, undefined, ocsdkLogger); try { await sdk.getChatToken(requestId, {}, -1); - throw new Error("Should throw an error"); + fail("Should throw an error"); } catch (error: any) { expect(error.message).toEqual("Invalid currentRetryCount"); expect(ocsdkLogger.log).toHaveBeenCalled(); @@ -222,8 +225,18 @@ describe("SDK unit tests", () => { expect(axios.create).toHaveBeenCalled(); expect(axiosRetryHandler.default).toHaveBeenCalled(); }); - }); + it("Should fail due to empty response", async () => { + spyOn(axios, "create").and.returnValue(axiosInstEmptyMock); + const sdk = new SDK(ochannelConfig as IOmnichannelConfiguration); + try { + await sdk.getChatToken(requestId, {}, 0); + fail("Should throw an error"); + } catch (error:any) { + expect(error.message).toEqual("Empty data received from getChatToken"); + } + }); + }); describe("Test getReconnectableChats method", () => { @@ -278,6 +291,8 @@ describe("SDK unit tests", () => { let browserName: any; let deviceType: any; let osType: any; + const HTTPTimeOutErrorMessage = SDKError.ClientHTTPTimeoutErrorName + ": " + SDKError.ClientHTTPTimeoutErrorMessage; + beforeEach(() => { locationInfo = { latitude: "1", longitude: "2" }; @@ -517,9 +532,7 @@ describe("SDK unit tests", () => { }); describe("Test getChatTranscripts method", () => { - const coolId = "coolId"; - const sessionInitOpt = { authenticatedUserToken: "asdas" }; @@ -630,7 +643,7 @@ describe("SDK unit tests", () => { const sdk = new SDK(ochannelConfig as IOmnichannelConfiguration); const result = sdk.validateAuthChatRecord(requestId, validateAuthChatRecordOptionalParams as IValidateAuthChatRecordOptionalParams); result.then(() => { - throw Error("Promise should reject"); + fail("Promise should reject"); }).catch(() => { expect(axiosInstMockInvalid).toHaveBeenCalled(); done(); @@ -679,7 +692,9 @@ describe("SDK unit tests", () => { let sdk: any; let requestBody: any; let originalTimeout:number; - + let mock: MockAdapter; + const HTTPTimeOutErrorMessage = `${SDKError.ClientHTTPTimeoutErrorName}: ${SDKError.ClientHTTPTimeoutErrorMessage}`; + beforeEach(() => { originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000; //set the environment variable @@ -690,120 +705,136 @@ describe("SDK unit tests", () => { chatId: "chatId" }; sdk = new SDK(ochannelConfig as IOmnichannelConfiguration); + mock = new MockAdapter(axios); requestBody = { body: "dummy" } }); it("getChatConfig timeout test", async () => { - spyOn(axios, "create").and.returnValue({ async get(endpoint: any) { return dataMock; }}); try { + mock.onGet(/.*/).timeout(); await sdk.getChatConfig(""); + fail("Should throw an error"); } catch (error: any) { - expect(error.code).toEqual("ECONNABORTED "); - expect(error.message).toContain("timeout"); - } + expect(error.code).toEqual("ECONNABORTED"); + expect(error.message).toContain("timeout"); } }); it("getChatToken timeout test", async () => { - spyOn(axios, "create").and.returnValue(axiosInstMock); try { + mock.onGet(/.*/).timeout(); await sdk.getChatToken(requestId, {}, 0); + fail("Should throw an error"); } catch (error: any) { - expect(error.message).toEqual(SDKError.ClientHTTPTimeoutErrorName + ":" + SDKError.ClientHTTPTimeoutErrorMessage); + expect(error.message).toEqual(HTTPTimeOutErrorMessage); } }); it("getReconnectableChats timeout test", async () => { - spyOn(axios, "create").and.returnValue(axiosInstMock); try { + mock.onGet(/.*/).timeout(); await sdk.getReconnectableChats({ authenticatedUserToken : "Token"} as IReconnectableChatsParams); + fail("Should throw an error"); } catch (error: any) { - expect(error.message).toEqual(SDKError.ClientHTTPTimeoutErrorName + ":" + SDKError.ClientHTTPTimeoutErrorMessage); + expect(error.message).toEqual(HTTPTimeOutErrorMessage); } }); it("getReconnectAvailability timeout test", async () => { - spyOn(axios, "create").and.returnValue(axiosInstMock); try { + mock.onGet(/.*/).timeout(); await sdk.getReconnectAvailability("reconnectId"); + fail("Should throw an error"); } catch (error: any) { - expect(error.message).toEqual(SDKError.ClientHTTPTimeoutErrorName + ":" + SDKError.ClientHTTPTimeoutErrorMessage); + expect(error.message).toEqual(HTTPTimeOutErrorMessage); } }); it("sessionInit timeout test", async () => { - spyOn(axios, "create").and.returnValue({ async get(endpoint: any) { return dataMock; }}); try { - sdk.sessionInit(requestId, defaultOpt as ISessionInitOptionalParams); + mock.onPost(/.*/).timeout(); + + await sdk.sessionInit(requestId, defaultOpt as ISessionInitOptionalParams); + fail("Should throw an error"); } catch (error: any) { - expect(error.message).toEqual(SDKError.ClientHTTPTimeoutErrorName + ":" + SDKError.ClientHTTPTimeoutErrorMessage); + expect(error.message).toEqual(HTTPTimeOutErrorMessage); } }); it("getAgentAvailability timeout test", async () => { - spyOn(axios, "create").and.returnValue({ async get(endpoint: any) { return dataMock; }}); try { - sdk.getAgentAvailability(requestId, defaultOpt as ISessionInitOptionalParams); + mock.onPost(/.*/).timeout(); + await sdk.getAgentAvailability(requestId, defaultOpt as ISessionInitOptionalParams); + fail("Should throw an error"); } catch (error: any) { - expect(error.message).toEqual(SDKError.ClientHTTPTimeoutErrorName + ":" + SDKError.ClientHTTPTimeoutErrorMessage); + expect(error.message).toEqual(HTTPTimeOutErrorMessage); } }); it("sessionClose timeout test", async () => { - spyOn(axios, "create").and.returnValue({ async get(endpoint: any) { return dataMock; }}); try { - sdk.sessionClose(requestId, defaultOpt as ISessionCloseOptionalParams); + mock.onPost(/.*/).timeout(); + + await sdk.sessionClose(requestId, defaultOpt as ISessionCloseOptionalParams); + fail("Should throw an error"); } catch (error: any) { - expect(error.code).toEqual("ECONNABORTED "); - expect(error.message).toContain("timeout"); + expect(error.message).toEqual(HTTPTimeOutErrorMessage); } }); it("submitPostChatResponse timeout test", async () => { - spyOn(axios, "create").and.returnValue({ async get(endpoint: any) { return dataMock; }}); try { - sdk.submitPostChatResponse(requestId, defaultOpt as ISubmitPostChatResponseOptionalParams); + mock.onPost(/.*/).timeout(); + + await sdk.submitPostChatResponse(requestId, defaultOpt as ISubmitPostChatResponseOptionalParams); + fail("Should throw an error"); } catch (error: any) { - expect(error.message).toEqual(SDKError.ClientHTTPTimeoutErrorName + ":" + SDKError.ClientHTTPTimeoutErrorMessage); + expect(error.message).toEqual(HTTPTimeOutErrorMessage); } }); it("getSurveyInviteLink timeout test", async () => { - spyOn(axios, "create").and.returnValue({ async get(endpoint: any) { return dataMock; }}); + try { - sdk.getSurveyInviteLink(requestId, defaultOpt as IGetSurveyInviteLinkOptionalParams); + mock.onPost(/.*/).timeout(); + await sdk.getSurveyInviteLink(requestId, defaultOpt as IGetSurveyInviteLinkOptionalParams); + fail("Should throw an error"); } catch (error: any) { - expect(error.message).toEqual(SDKError.ClientHTTPTimeoutErrorName + ":" + SDKError.ClientHTTPTimeoutErrorMessage); + expect(error.message).toEqual(HTTPTimeOutErrorMessage); } }); it("getChatTranscripts timeout test", async () => { - spyOn(axios, "create").and.returnValue({ async get(endpoint: any) { return dataMock; }}); try { - sdk.getChatTranscripts(requestId, "coolId", "coolId", defaultOpt as IGetChatTranscriptsOptionalParams); + mock.onGet(/.*/).timeout(); + await sdk.getChatTranscripts(requestId, "coolId", "coolId", defaultOpt as IGetChatTranscriptsOptionalParams); + fail("Should throw an error"); } catch (error: any) { - expect(error.message).toEqual(SDKError.ClientHTTPTimeoutErrorName + ":" + SDKError.ClientHTTPTimeoutErrorMessage); + expect(error.message).toEqual(HTTPTimeOutErrorMessage); } }); it("makeSecondaryChannelEventRequest timeout test", async () => { - spyOn(axios, "create").and.returnValue({ async get(endpoint: any) { return dataMock; }}); try { - sdk.makeSecondaryChannelEventRequest(requestId, requestBody, defaultOpt as ISecondaryChannelEventOptionalParams); + mock.onPost(/.*/).timeout(); + await sdk.makeSecondaryChannelEventRequest(requestId, requestBody, defaultOpt as ISecondaryChannelEventOptionalParams); + fail("Should throw an error"); } catch (error: any) { - expect(error.message).toEqual(SDKError.ClientHTTPTimeoutErrorName + ":" + SDKError.ClientHTTPTimeoutErrorMessage); + expect(error.message).toEqual(HTTPTimeOutErrorMessage); } }); it("validateAuthChatRecord timeout test", async () => { - spyOn(axios, "create").and.returnValue({ async get(endpoint: any) { return dataMock; }}); try { - sdk.validateAuthChatRecord(requestId, defaultOpt as IValidateAuthChatRecordOptionalParams); + mock.onGet(/.*/).timeout(); + await sdk.validateAuthChatRecord(requestId, defaultOpt as IValidateAuthChatRecordOptionalParams); + fail("Should throw an error"); } catch (error: any) { - expect(error.message).toEqual(SDKError.ClientHTTPTimeoutErrorName + ":" + SDKError.ClientHTTPTimeoutErrorMessage); + expect(error.message).toEqual(HTTPTimeOutErrorMessage); } }); afterEach(() => { + mock.restore(); jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; //remove environment variable }); });