import fetchMock from 'fetch-mock'; import { afterEach, describe, expect, it } from 'vitest'; import { handleDelete, handleFetch, stringifyQuery } from './helpers'; import { CmsError, ReferenceError, UnauthorizedError } from './errors'; const url = '/test/'; const successResponse = { status: 200, body: { success: true } }; describe('Api helpers', () => { afterEach(() => { fetchMock.restore(); }); it('should return the fetched response if status is 200', async () => { fetchMock.get(/test/, successResponse); const res = await handleFetch(url); expect(res.status).toEqual(200); }); it('should return the json body properly if status is 200', async () => { fetchMock.get(/test/, successResponse); const res = await handleFetch(url); const json = await res.json(); expect(json).toEqual({ success: true }); }); it('should properly post json and return response', async () => { fetchMock.post(/test/, successResponse); const res = await handleFetch(url, { method: 'post', body: JSON.stringify({ foo: 'bar' }) }); expect(res.status).toEqual(200); }); it('should throw an unauthorized error if the server returns a 401', async () => { fetchMock.get(/test/, { status: 401, body: { success: false } }); try { await handleFetch(url); } catch (e) { expect(e).toBeInstanceOf(UnauthorizedError); expect(e.message).toEqual(`Deze gebruiker heeft geen toegang tot /api${url}`); } }); it('should throw a http error if the response is not ok', async () => { fetchMock.get(/test/, { status: 500, body: { success: false } }); try { await handleFetch(url); } catch (e) { expect(e).toBeInstanceOf(CmsError); } }); it('should handle empty error responses', async () => { fetchMock.get(/test/, { status: 500 }); try { await handleFetch(url); } catch (e) { expect(e).toBeInstanceOf(CmsError); } }); it('should throw a reference error if the server returns a 3001 error code on delete', async () => { fetchMock.delete(/test/, { status: 400, body: { success: false, errorCode: 3001 } }); try { await handleDelete(url); } catch (e) { expect(e).toBeInstanceOf(ReferenceError); expect(e.originalError).toBeInstanceOf(Error); } }); it('should properly stringify query params', () => { const params = { test: true, hello: 'world', number: 42 }; const path = 'http://test.com'; const qs = `${path}?test=true&hello=world&number=42`; expect(stringifyQuery(path, params)).toEqual(qs); }); });