From b8adf5f2747d7774d34bf600cfdb3f6ef6634e35 Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Thu, 17 Nov 2022 21:30:42 +0100 Subject: [PATCH] Created test for HttpClient --- src/utils/types.ts | 2 -- test/common/services/HttpClient.test.ts | 37 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 test/common/services/HttpClient.test.ts diff --git a/src/utils/types.ts b/src/utils/types.ts index 3009bcf7..953c1981 100644 --- a/src/utils/types.ts +++ b/src/utils/types.ts @@ -1,5 +1,3 @@ export type MediaMatcher = (query: string) => MediaQueryList; export type Fetch = typeof window.fetch; - -export type JsonFetch = (url: string, options?: RequestInit) => Promise; diff --git a/test/common/services/HttpClient.test.ts b/test/common/services/HttpClient.test.ts new file mode 100644 index 00000000..63a2307d --- /dev/null +++ b/test/common/services/HttpClient.test.ts @@ -0,0 +1,37 @@ +import { HttpClient } from '../../../src/common/services/HttpClient'; + +describe('HttpClient', () => { + const fetch = jest.fn(); + const httpClient = new HttpClient(fetch); + + beforeEach(jest.clearAllMocks); + + describe('fetchJson', () => { + it('throws json when response is not ok', async () => { + const theError = { error: true, foo: 'bar' }; + fetch.mockResolvedValue({ json: () => theError, ok: false }); + + await expect(httpClient.fetchJson('')).rejects.toEqual(theError); + }); + + it('return json when response is ok', async () => { + const theJson = { foo: 'bar' }; + fetch.mockResolvedValue({ json: () => theJson, ok: true }); + + const result = await httpClient.fetchJson(''); + + expect(result).toEqual(theJson); + }); + }); + + describe('fetchBlob', () => { + it('returns response as blob', async () => { + const theBlob = new Blob(); + fetch.mockResolvedValue({ blob: () => theBlob }); + + const result = await httpClient.fetchBlob(''); + + expect(result).toEqual(theBlob); + }); + }); +});