|
| 1 | +/** |
| 2 | + * @vitest-environment node |
| 3 | + */ |
| 4 | +import { authMockFns } from '@sim/testing' |
| 5 | +import { NextRequest } from 'next/server' |
| 6 | +import { beforeEach, describe, expect, it, vi } from 'vitest' |
| 7 | + |
| 8 | +const mocks = vi.hoisted(() => ({ search: vi.fn() })) |
| 9 | +vi.mock('@/lib/knowledge/application/search', () => ({ |
| 10 | + searchKnowledge: { operation: { id: 'knowledge.search' }, execute: mocks.search }, |
| 11 | +})) |
| 12 | + |
| 13 | +import { POST } from '@/app/api/knowledge/search/route' |
| 14 | + |
| 15 | +describe('workspace search route', () => { |
| 16 | + beforeEach(() => { |
| 17 | + vi.clearAllMocks() |
| 18 | + authMockFns.mockGetSession.mockResolvedValue({ |
| 19 | + user: { id: 'user-1', email: 'reader@fixture.test', name: 'Reader' }, |
| 20 | + session: { id: 'session-1' }, |
| 21 | + }) |
| 22 | + mocks.search.mockResolvedValue({ results: [], knowledgeBases: [] }) |
| 23 | + }) |
| 24 | + |
| 25 | + it('passes the authenticated request cancellation signal through the existing operation', async () => { |
| 26 | + const controller = new AbortController() |
| 27 | + const request = new NextRequest('http://localhost/api/knowledge/search', { |
| 28 | + method: 'POST', |
| 29 | + headers: { 'content-type': 'application/json' }, |
| 30 | + body: JSON.stringify({ |
| 31 | + workspaceId: 'workspace-1', |
| 32 | + knowledgeBaseIds: ['kb-1'], |
| 33 | + query: 'Orion', |
| 34 | + }), |
| 35 | + signal: controller.signal, |
| 36 | + }) |
| 37 | + const response = await POST(request) |
| 38 | + expect(response.status).toBe(200) |
| 39 | + const call = mocks.search.mock.calls[0][0] |
| 40 | + expect(call.principal).toEqual({ kind: 'session', userId: 'user-1', sessionId: 'session-1' }) |
| 41 | + expect(call.input.signal).toBe(request.signal) |
| 42 | + controller.abort() |
| 43 | + expect(call.input.signal.aborted).toBe(true) |
| 44 | + await expect(response.json()).resolves.toEqual({ |
| 45 | + success: true, |
| 46 | + data: { query: 'Orion', results: [] }, |
| 47 | + }) |
| 48 | + }) |
| 49 | + |
| 50 | + it('authenticates before parsing and never enters search for an anonymous request', async () => { |
| 51 | + authMockFns.mockGetSession.mockResolvedValueOnce(null) |
| 52 | + const response = await POST( |
| 53 | + new NextRequest('http://localhost/api/knowledge/search', { |
| 54 | + method: 'POST', |
| 55 | + body: '{', |
| 56 | + headers: { 'content-type': 'application/json' }, |
| 57 | + }) |
| 58 | + ) |
| 59 | + expect(response.status).toBe(401) |
| 60 | + expect(mocks.search).not.toHaveBeenCalled() |
| 61 | + }) |
| 62 | +}) |
0 commit comments