From c6bc3b379897257310c842b490c3757d84e5ac1f Mon Sep 17 00:00:00 2001 From: MareStare Date: Tue, 4 Mar 2025 02:45:21 +0000 Subject: [PATCH] Add tests for the `HttpClient` --- assets/js/utils/__tests__/http-client.spec.ts | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 assets/js/utils/__tests__/http-client.spec.ts diff --git a/assets/js/utils/__tests__/http-client.spec.ts b/assets/js/utils/__tests__/http-client.spec.ts new file mode 100644 index 00000000..870c5e87 --- /dev/null +++ b/assets/js/utils/__tests__/http-client.spec.ts @@ -0,0 +1,58 @@ +import { HttpClient } from '../http-client'; +import { fetchMock } from '../../../test/fetch-mock'; + +describe('HttpClient', () => { + beforeAll(() => { + vi.useFakeTimers(); + fetchMock.enableMocks(); + }); + + afterEach(() => { + fetchMock.resetMocks(); + }); + + it('should throw an HttpError on non-OK responses', async () => { + const client = new HttpClient(); + + fetchMock.mockResponse('Not Found', { status: 404, statusText: 'Not Found' }); + + await expect(client.fetch('/', {})).rejects.toThrowError(/404: Not Found/); + + // 404 is non-retryable + expect(fetch).toHaveBeenCalledOnce(); + }); + + it('should retry 500 errors', async () => { + const client = new HttpClient(); + + fetchMock.mockResponses( + ['Internal Server Error', { status: 500, statusText: 'Internal Server Error' }], + ['OK', { status: 200, statusText: 'OK' }], + ); + + const promise = expect(client.fetch('/', {})).resolves.toMatchObject({ status: 200, statusText: 'OK' }); + await vi.runAllTimersAsync(); + await promise; + + expect(fetch).toHaveBeenCalledTimes(2); + }); + + it('should not retry AbortError', async () => { + const client = new HttpClient(); + + fetchMock.mockResponse('OK', { status: 200, statusText: 'OK' }); + + const abortController = new AbortController(); + + const promise = expect(client.fetch('/', { signal: abortController.signal })).rejects.toThrowError( + 'The operation was aborted.', + ); + + abortController.abort(); + + await vi.runAllTimersAsync(); + await promise; + + expect(fetch).toHaveBeenCalledOnce(); + }); +});