From 322979a0d83876b3a38386b64f612cd516cabb0e Mon Sep 17 00:00:00 2001 From: Tudor Stanciu Date: Sat, 11 Feb 2023 04:01:15 +0200 Subject: [PATCH] 100% test coverage --- jestconfig.json | 2 +- src/__tests__/TuitioAuthentication.test.ts | 36 ++++++++++++++++++++++ src/client.ts | 11 +++---- 3 files changed, 42 insertions(+), 7 deletions(-) diff --git a/jestconfig.json b/jestconfig.json index a780067..b5e6a9b 100644 --- a/jestconfig.json +++ b/jestconfig.json @@ -4,7 +4,7 @@ }, "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$", "moduleFileExtensions": ["ts", "tsx", "js", "jsx", "json", "node"], - "collectCoverage": false, + "collectCoverage": true, "coverageThreshold": { "global": { "branches": 50, diff --git a/src/__tests__/TuitioAuthentication.test.ts b/src/__tests__/TuitioAuthentication.test.ts index c885de0..6c4fcc1 100644 --- a/src/__tests__/TuitioAuthentication.test.ts +++ b/src/__tests__/TuitioAuthentication.test.ts @@ -30,3 +30,39 @@ test("Tuitio client authentication", async () => { const emptyStorage = fetch(); expect(emptyStorage.userName).toBeNull(); }); + +test("Tuitio client failed authentication", async () => { + (axios.request as jest.Mock).mockRejectedValueOnce({ + response: { + status: 500, + data: { title: "Internal server error" } + } + }); + + const client = new TuitioClient("https://test.com/api"); + + try { + await client.authenticate("user", "pass"); + } catch (error: any) { + expect(error.title).toBe("Internal server error"); + expect(error.message).toBe("Internal server error"); + } +}); + +test("Tuitio client failed authentication with unhandled exception", async () => { + (axios.request as jest.Mock).mockRejectedValueOnce({ + response: { + status: 500, + error: { message: "Internal server error" } + } + }); + + const client = new TuitioClient("https://test.com/api"); + + try { + await client.authenticate("user", "pass"); + } catch (error: any) { + expect(error.response.status).toBe(500); + expect(error.response.error.message).toBe("Internal server error"); + } +}); diff --git a/src/client.ts b/src/client.ts index c883a97..6fdc5b0 100644 --- a/src/client.ts +++ b/src/client.ts @@ -11,12 +11,11 @@ async function request(url: string, method: string) { return res.data; } catch (error: any) { if (error.response && error.response.data) { - throw ( - { - ...error.response.data, - message: error.response.data.detail || error.response.data.title - } || error - ); + const { detail, title } = error.response.data; + throw { + ...error.response.data, + message: detail || title + }; } throw error; }