Files
THE-TIP-TOP/frontend/src/test/unit/game.service.test.js
Emma781227 b6506435d5 test
2026-07-20 10:35:35 +02:00

69 lines
2.2 KiB
JavaScript

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { myGainsApi, participateApi } from '../../services/game'
// Tests unitaires du service game : on mocke fetch, aucune vraie requête HTTP.
const mockFetch = vi.fn()
function jsonResponse(body, { ok = true, status = 200 } = {}) {
return Promise.resolve({ ok, status, json: () => Promise.resolve(body) })
}
beforeEach(() => {
vi.stubGlobal('fetch', mockFetch)
mockFetch.mockReset()
localStorage.setItem('token', 'mon-jwt')
})
afterEach(() => {
vi.unstubAllGlobals()
})
describe('myGainsApi', () => {
it('appelle /api/game/my-gains avec le token et renvoie les gains', async () => {
const payload = { gains: [{ id: 1, name: 'Thé détox' }] }
mockFetch.mockReturnValue(jsonResponse(payload))
const data = await myGainsApi()
expect(data).toEqual(payload)
expect(mockFetch).toHaveBeenCalledWith('/api/game/my-gains', {
headers: { Authorization: 'Bearer mon-jwt' },
})
})
it("lève une erreur avec le status en cas d'échec (ex: session expirée)", async () => {
mockFetch.mockReturnValue(
jsonResponse({ message: 'Non autorisé.' }, { ok: false, status: 401 })
)
await expect(myGainsApi()).rejects.toMatchObject({ message: 'Non autorisé.', status: 401 })
})
})
describe('participateApi', () => {
it('envoie le code en POST avec le token', async () => {
const payload = { gain: { name: 'Thé signature' }, claim: { id: 1 } }
mockFetch.mockReturnValue(jsonResponse(payload))
const data = await participateApi('ABCDE12345')
expect(data).toEqual(payload)
expect(mockFetch).toHaveBeenCalledWith('/api/game/participate', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer mon-jwt',
},
body: JSON.stringify({ code: 'ABCDE12345' }),
})
})
it("transmet le message d'erreur de l'API (code déjà utilisé, invalide...)", async () => {
mockFetch.mockReturnValue(
jsonResponse({ message: 'Ce code a déjà été utilisé.' }, { ok: false, status: 400 })
)
await expect(participateApi('ABCDE12345')).rejects.toThrow('Ce code a déjà été utilisé.')
})
})