From 867fa49568f8e799647e08c0664e852c4a04373c Mon Sep 17 00:00:00 2001 From: Kulbhushan Kaushik Date: Tue, 11 Oct 2022 12:19:03 -0400 Subject: [PATCH] global-methods unit tests --- src/global-methods.spec.js | 77 +++++++++++++++++++++++++++++++++++++- 1 file changed, 75 insertions(+), 2 deletions(-) diff --git a/src/global-methods.spec.js b/src/global-methods.spec.js index a4c46989..286fe976 100644 --- a/src/global-methods.spec.js +++ b/src/global-methods.spec.js @@ -1,4 +1,77 @@ import axios from 'axios'; -import '@/global-methods.js'; +import globalMethods from "@/global-methods"; -test.todo("Need to add some tests here"); \ No newline at end of file +//Mock external dependencies +jest.mock("axios"); + +it("Global Methods - Call Http Client - Should Resolve Promise", () => { + //Arrange + const endpoint = "https://mock.safelite.com"; + const httpArgs = setupMocksForHttpClient({ endpoint: endpoint }); + + //Act + globalMethods.callHttpClient(httpArgs).then((response) => { + //Assert + expect(axios.mock.calls[0][0].url).toContain(endpoint); + expect(response.data.message).toContain("Success"); + expect(response.status).toEqual(200); + }); + }); + + it("Global Methods - Call Http Client - Should Reject Promise", () => { + //Arrange + const endpoint = "https://mock.safelite.com"; + const httpArgs = setupMocksForHttpClient({ + endpoint: endpoint, + isError: true, + }); + + //Act + globalMethods.callHttpClient(httpArgs).catch((err) => { + //Assert + expect(axios.mock.calls[0][0].url).toContain(endpoint); + expect(err.data.message).toContain("Error"); + expect(err.status).toEqual(500); + }); + }); + + function setupMocksForHttpClient({ + endpoint = null, + isError = false, + additionalData = null, + }) { + //Clear node module + axios.mockClear(); + + // Success Response + const response = { + status: 200, + data: { + message: "Success", + additionalData: additionalData, + }, + }; + + // Error Response + const error = { + response: { + status: 500, + data: { + message: "Error", + additionalData: additionalData, + }, + }, + }; + + // Error interceptor on Axios returns a different object, so we need to mimic that. + if (isError) { + axios.mockRejectedValue(error); + } else { + axios.mockResolvedValue(response); + } + + return { + endpoint: endpoint, + logApiCall: true + }; + } \ No newline at end of file