From 2ec68a2343325626828fb66a48bc0b417332398f Mon Sep 17 00:00:00 2001 From: Jeremiah Date: Mon, 24 Apr 2023 09:21:30 -0400 Subject: [PATCH] test: add fetchQutoes test --- js/quote.test.js | 49 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/js/quote.test.js b/js/quote.test.js index 4f65dce..d08f343 100644 --- a/js/quote.test.js +++ b/js/quote.test.js @@ -1,4 +1,4 @@ -import { getRandomQuote } from './quote'; +import { getRandomQuote, fetchQuotes } from './quote'; describe('getRandomQuote', () => { test('returns a random quote from an array of quotes', () => { @@ -10,4 +10,51 @@ describe('getRandomQuote', () => { const randomQuote = getRandomQuote(sampleQuotes); expect(sampleQuotes).toContain(randomQuote); }); +}); + + +describe('fetchQuotes', () => { + it('should return an array of quotes', async () => { + const quotes = await fetchQuotes(); + expect(Array.isArray(quotes)).toBe(true); + }); + + it('should throw an error if the server returns an error status', async () => { + // Mock a failed fetch response + global.fetch = jest.fn(() => + Promise.resolve({ + ok: false, + status: 404, + statusText: 'Not Found', + }), + ); + + try { + await fetchQuotes(); + } catch (error) { + expect(error.message).toBe('Server returned 404 Not Found'); + } + + // Restore the original fetch function + global.fetch.mockRestore(); + }); + + it('should throw an error if the data structure is invalid', async () => { + // Mock an invalid fetch response + global.fetch = jest.fn(() => + Promise.resolve({ + ok: true, + json: () => Promise.resolve({}), + }), + ); + + try { + await fetchQuotes(); + } catch (error) { + expect(error.message).toBe('Invalid data structure: missing quotes array'); + } + + // Restore the original fetch function + global.fetch.mockRestore(); + }); }); \ No newline at end of file