import { describe, it, expect, beforeAll } from 'vitest'; import request from 'supertest'; import { setup } from './helpers.js'; import { pool } from '../../lib/db/pool.js'; let app, ownerHeaders; beforeAll(async () => { ({ app, ownerHeaders } = await setup()); }); describe('spaces routes', () => { it('GET /api/spaces empty returns []', async () => { const res = await request(app).get('/api/spaces').set(ownerHeaders); expect(res.status).toBe(200); expect(res.body).toEqual([]); }); it('GET /api/spaces without auth → 401', async () => { const res = await request(app).get('/api/spaces'); expect(res.status).toBe(401); }); it('POST /api/spaces creates 201 and persists', async () => { const res = await request(app).post('/api/spaces').set(ownerHeaders) .send({ slug: 'home', name: 'Home' }); expect(res.status).toBe(201); expect(res.body.slug).toBe('home'); expect(res.body.id).toBeDefined(); const { rows } = await pool.query('SELECT slug FROM spaces WHERE id=$1', [res.body.id]); expect(rows[0].slug).toBe('home'); }); it('POST /api/spaces with bad slug → 400 with details', async () => { const res = await request(app).post('/api/spaces').set(ownerHeaders) .send({ slug: 'Bad Slug!', name: 'X' }); expect(res.status).toBe(400); expect(res.body.error.code).toBe('validation_failed'); expect(Array.isArray(res.body.error.details)).toBe(true); }); it('GET /api/spaces/:id returns the row', async () => { const created = await request(app).post('/api/spaces').set(ownerHeaders) .send({ slug: 'getme', name: 'Get Me' }); const res = await request(app).get(`/api/spaces/${created.body.id}`).set(ownerHeaders); expect(res.status).toBe(200); expect(res.body.id).toBe(created.body.id); }); it('GET /api/spaces/by-slug/:slug returns the row', async () => { await request(app).post('/api/spaces').set(ownerHeaders) .send({ slug: 'lookup', name: 'Lookup' }); const res = await request(app).get('/api/spaces/by-slug/lookup').set(ownerHeaders); expect(res.status).toBe(200); expect(res.body.slug).toBe('lookup'); }); it('GET unknown id → 404', async () => { const res = await request(app) .get('/api/spaces/00000000-0000-0000-0000-000000000000').set(ownerHeaders); expect(res.status).toBe(404); }); it('PATCH updates fields', async () => { const created = await request(app).post('/api/spaces').set(ownerHeaders) .send({ slug: 'patch', name: 'Patch' }); const res = await request(app).patch(`/api/spaces/${created.body.id}`).set(ownerHeaders) .send({ name: 'Patched' }); expect(res.status).toBe(200); expect(res.body.name).toBe('Patched'); }); it('DELETE returns 204 then GET 404', async () => { const created = await request(app).post('/api/spaces').set(ownerHeaders) .send({ slug: 'del', name: 'Del' }); const del = await request(app).delete(`/api/spaces/${created.body.id}`).set(ownerHeaders); expect(del.status).toBe(204); const get = await request(app).get(`/api/spaces/${created.body.id}`).set(ownerHeaders); expect(get.status).toBe(404); }); });