From cc1f4331cd4f7f9c5d662925fd97d2c035f90812 Mon Sep 17 00:00:00 2001 From: Frank Date: Mon, 15 Nov 2021 12:41:46 -0500 Subject: [PATCH] Added global-methods unit tests --- src/global-methods.js | 5 ++- src/global-methods.spec.js | 73 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 src/global-methods.spec.js diff --git a/src/global-methods.js b/src/global-methods.js index f2ad4f043..0b33cf613 100644 --- a/src/global-methods.js +++ b/src/global-methods.js @@ -29,8 +29,11 @@ export default { ); }); }, - // For mock use only! + + + /* istanbul ignore next */ callMockHttpClient({ method, endpoint}) { + // For Mock use only! return new Promise((resolve, reject) => { axios({ diff --git a/src/global-methods.spec.js b/src/global-methods.spec.js new file mode 100644 index 000000000..6885a23e0 --- /dev/null +++ b/src/global-methods.spec.js @@ -0,0 +1,73 @@ +import globalMethods from "@/global-methods"; +import axios from 'axios'; + +//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 + } +} \ No newline at end of file