From 24f4f658536b8808ce036f305f42d73981e3401a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20FAMIBELLE-PRONZOLA?= Date: Sat, 4 Jul 2026 01:17:06 +0400 Subject: [PATCH] =?UTF-8?q?fix:=20request()=20l=C3=A8ve=20une=20erreur=20c?= =?UTF-8?q?laire=20sur=20r=C3=A9ponse=20HTTP=20non-ok?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/__tests__/oki-api.test.js | 37 +++++++++++++++++++++++++++++++++++ lib/oki-api.js | 10 ++++++++-- 2 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 lib/__tests__/oki-api.test.js 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) {