|
| 1 | +/** |
| 2 | + * @vitest-environment node |
| 3 | + */ |
| 4 | +import { afterEach, describe, expect, it, vi } from 'vitest' |
| 5 | +import { z } from 'zod' |
| 6 | +import { requestJson } from '@/lib/api/client/request' |
| 7 | +import { listKnowledgeDocumentsContract } from '@/lib/api/contracts/knowledge' |
| 8 | +import { defineRouteContract } from '@/lib/api/contracts/types' |
| 9 | + |
| 10 | +/** |
| 11 | + * Captures the URL of the last fetch call and returns a valid JSON response so |
| 12 | + * `requestJson`'s response validation passes. |
| 13 | + */ |
| 14 | +function mockFetchReturning(body: unknown) { |
| 15 | + const fetchMock = vi.fn( |
| 16 | + async () => |
| 17 | + new Response(JSON.stringify(body), { |
| 18 | + status: 200, |
| 19 | + headers: { 'content-type': 'application/json' }, |
| 20 | + }) |
| 21 | + ) |
| 22 | + vi.stubGlobal('fetch', fetchMock) |
| 23 | + return fetchMock |
| 24 | +} |
| 25 | + |
| 26 | +describe('requestJson query serialization', () => { |
| 27 | + afterEach(() => { |
| 28 | + vi.unstubAllGlobals() |
| 29 | + }) |
| 30 | + |
| 31 | + it('serializes a JSON-string query param verbatim (regression: tagFilters)', async () => { |
| 32 | + const fetchMock = mockFetchReturning({ |
| 33 | + success: true, |
| 34 | + data: { |
| 35 | + documents: [], |
| 36 | + pagination: { total: 0, limit: 50, offset: 0, hasMore: false }, |
| 37 | + }, |
| 38 | + }) |
| 39 | + |
| 40 | + const tagFilters = JSON.stringify([ |
| 41 | + { tagSlot: 'tag1', fieldType: 'text', operator: 'contains', value: 'Ada Lovelace' }, |
| 42 | + ]) |
| 43 | + |
| 44 | + await requestJson(listKnowledgeDocumentsContract, { |
| 45 | + params: { id: 'kb-1' }, |
| 46 | + query: { tagFilters }, |
| 47 | + }) |
| 48 | + |
| 49 | + const calledUrl = String(fetchMock.mock.calls[0][0]) |
| 50 | + const url = new URL(calledUrl, 'https://example.test') |
| 51 | + // The param must round-trip as the exact JSON, never "[object Object]". |
| 52 | + expect(url.searchParams.get('tagFilters')).toBe(tagFilters) |
| 53 | + expect(calledUrl).not.toContain('object+Object') |
| 54 | + expect(calledUrl).not.toContain('[object Object]') |
| 55 | + }) |
| 56 | + |
| 57 | + it('throws instead of silently corrupting an array-of-objects query param', async () => { |
| 58 | + mockFetchReturning({ ok: true }) |
| 59 | + |
| 60 | + const badContract = defineRouteContract({ |
| 61 | + method: 'GET', |
| 62 | + path: '/api/test', |
| 63 | + query: z.object({ items: z.array(z.object({ a: z.string() })) }), |
| 64 | + response: { mode: 'json', schema: z.object({ ok: z.boolean() }) }, |
| 65 | + }) |
| 66 | + |
| 67 | + await expect(requestJson(badContract, { query: { items: [{ a: 'x' }] } })).rejects.toThrow( |
| 68 | + /arrays of objects are not URL-safe/ |
| 69 | + ) |
| 70 | + }) |
| 71 | +}) |
0 commit comments