diff --git a/lib/__tests__/oki-api.test.js b/lib/__tests__/oki-api.test.js new file mode 100644 index 0000000..0fcb3bc --- /dev/null +++ b/lib/__tests__/oki-api.test.js @@ -0,0 +1,37 @@ +import {describe, it, expect, vi, afterEach} from 'vitest' +import {jwennAnTeks} from '../oki-api' + +describe('request (via jwennAnTeks)', () => { + const originalFetch = global.fetch + + afterEach(() => { + global.fetch = originalFetch + vi.restoreAllMocks() + }) + + it('returns the parsed body on a successful response', async () => { + global.fetch = vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({id: 1, titre: 'Test'}) + }) + + const result = await jwennAnTeks(1, 'token') + expect(result).toEqual({id: 1, titre: 'Test'}) + }) + + it('throws a clear error when Strapi returns an error response', async () => { + global.fetch = vi.fn().mockResolvedValue({ + ok: false, + status: 400, + json: async () => ({data: null, error: {status: 400, name: 'ValidationError', message: 'Invalid key'}}) + }) + + await expect(jwennAnTeks(1, 'token')).rejects.toThrow('Eshwe pu jwenn done-a') + }) + + it('throws when the network request itself fails', async () => { + global.fetch = vi.fn().mockRejectedValue(new TypeError('network down')) + + await expect(jwennAnTeks(1, 'token')).rejects.toThrow('Eshwe pu jwenn done-a') + }) +}) diff --git a/lib/oki-api.js b/lib/oki-api.js index af2a6c8..3a5fbbc 100644 --- a/lib/oki-api.js +++ b/lib/oki-api.js @@ -14,12 +14,18 @@ const headers = { async function request(url, opts = {}) { const {...options} = opts + let res try { - const res = await fetch(`${OKI_API}${url}`, options) - return res.json() + res = await fetch(`${OKI_API}${url}`, options) } catch { throw new Error('Eshwe pu jwenn done-a') } + + if (!res.ok) { + throw new Error('Eshwe pu jwenn done-a') + } + + return res.json() } export async function jwennTeksEpiSlug(slug) {